If I call getMeasuredWidth() or getWidth() for layout in onResume they return 0

前端 未结 7 2048
深忆病人
深忆病人 2020-11-28 09:10

If I call getMeasuredWidth() or getWidth() for layout in onResume they returns 0. I think that view it\'s not drawn yet in this moment.

Also I think that I need to

7条回答
  •  盖世英雄少女心
    2020-11-28 09:37

    Solution #1: To do it dynamically, you need a tag. A tag is basically a way for views to have memories. So save the convertView in another class (MyTag). So inside your java file:

    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;
        }
    

    Solution #2: Hard-code it. Pre-set the width. Inside your res/values/dimens.xml file, include

    50dp
    

    Then inside your res/layout/your_layout.xml file, include

            

    Then inside your java file:

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

提交回复
热议问题