Подтвердить что ты не робот

Если я назову getMeasuredWidth() или getWidth() для макета в onResume, они возвращают 0

Если я вызываю getMeasuredWidth() или getWidth() для макета в onResume, он возвращает 0. Я думаю, что в этот момент это еще не нарисовано.

Также я думаю, что мне нужно поместить getMeasuredWidth() или getWidth() в метод обратного вызова, вызванный после того, как макет рисуется и известны измерения. Какой метод обратного вызова для Android следует использовать?

4b9b3361

Ответ 1

Вы не можете использовать width/height/getMeasuredWidth/getMeasuredHeight на a View, прежде чем система отобразит его (обычно от onCreate/onResume).

Простым решением для этого является размещение Runnable в макете. Запуск будет выполнен после того, как будет выложен View.

BoxesLayout = (RelativeLayout) findViewById(R.id.BoxesLinearLayout);
BoxesLayout.post(new Runnable() {
    @Override
    public void run() {
        int w = BoxesLayout.getMeasuredWidth();
        int h = BoxesLayout.getMeasuredHeight();

        ...
    }
});

Ответ 2

В этом ответе говорится:

Используйте ViewTreeObserver в View, чтобы дождаться первого макета. Только после того, как первый макет будет работать getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight().

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      viewWidth = mediaGallery.getWidth();
      viewHeight = mediaGallery.getHeight();
    }
  });
}

Ответ 3

вы можете переопределить onLayout() в своем представлении; это используется android для размещения каждого из детей, которые есть в представлении, поэтому вы можете делать то, что хотите сделать после вызова super(..).

Ответ 4

В самом деле, кажется, что если макет не показан на экране, метод getWidth() возвращает 0. Что, кажется, работает для меня, вызывает метод measure() перед вызовом getMeasuredWidth() или getMesuredHeight(). Для метода меры я использовал аргументы Layout.WRAP_CONTENT, чтобы получить измерение того, что содержит макет.

Надеюсь, это поможет, Mihai

Ответ 6

Решение №1: Чтобы сделать это динамически, вам нужен тег. Тег - это в основном способ просмотра воспоминаний. Поэтому сохраните convertView в другом классе (MyTag). Итак, внутри вашего java файла:

private LayoutInflater layoutInflater;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MyTag holder = null;
    View row = convertView;
    if (row == null) {
      //Inflate the view however u can  
String strInflater = Context.LAYOUT_INFLATER_SERVICE;
        layoutInflater = (LayoutInflater) context.getSystemService(strInflater);
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResID, parent, false);
               holder = new MyTag();

            holder.itemName = (TextView) row.findViewById(R.id.example_itemname);
            holder.icon = (ImageView) row.findViewById(R.id.example_image);
            holder.button1 = (Button) row.findViewById(R.id.swipe_button1);
            holder.button2 = (Button) row.findViewById(R.id.swipe_button2);
            holder.button3 = (Button) row.findViewById(R.id.swipe_button3);
            row.setTag(holder);
        } else {
            holder = (MyTag) row.getTag();
        }

        holder.itemName.setText(itemdata.getItemName());
        System.out.println("holder.button3.getMeasuredWidth()= "+ holder.button3.getMeasuredWidth());
        System.out.println("holder.button3.getWidth()= "+ holder.button3.getWidth());

return row;
} //End of getView()


static class MyTag {  //It also works if not static

        TextView itemName;
        ImageView icon;
        Button button1;
        Button button2;
        Button button3;
    }

Решение №2: Жестко-кодируйте его. Предварительно установите ширину. Внутри файла res/values ​​/dimens.xml укажите

<dimen name="your_button_width">50dp</dimen>

Затем внутри файла res/layout/your_layout.xml включите

        <Button  
         android:layout_width="@dimen/your_button_width"  />

Затем внутри вашего java файла:

int buttonSize= (int) (context.getResources().getDimension(R.dimen.your_button_width));

Ответ 7

Используйте код ниже:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
   super.onWindowFocusChanged(hasFocus);
   Log.e("WIDTH",""+view.getWidth());
   Log.e("HEIGHT",""+view.getHeight());
}