How to inflate Android View in LinearLayout class?

后端 未结 3 1930
深忆病人
深忆病人 2021-01-04 18:17

I\'ve got a little piece of xml, which I\'ll be using in a lot of places in my app. For this reason I want to store it in a separate file. So I created mywidget.xml in which

相关标签:
3条回答
  • 2021-01-04 18:36

    The View class has an inflate method which wraps LayoutInflater.inflate. You should be able to use:

    LinearLayout ll = (LinearLayout) inflate(context, R.layout.amount_widget, this);
    

    to inflate your widget from xml. The call to addView() won't be needed, as inflate will add the newly inflated view for you!

    Edit: Just a note, because this View is already a LinearLayout, there's no need to have the root of the xml you're inflating also be a LinearLayout. It can increase your performance if you inflate only the EditText and just add that to the parent, rather than nesting a second LinearLayout within the parent. You can set the LinearLayout attributes (such as background and padding) directly on the AmountWidget wherever it's added in xml. This shouldn't matter too much in this specific case, but may be good to know going forward if you have a situation with many nested views.

    Edit2: The View class has three constructors: View(Context), View(Context, AttributeSet), and View(Context, AttributeSet, int). When the system inflates a view from xml, it will use one of the latter two. Any custom View will need to implement all three of these constructors. An easy way to do this while reusing your code is like this:

    public AmountWidget(Context context) {
        super(context);
        LinearLayout ll = (LinearLayout) inflate(context, R.layout.amount_widget, this);
    }
    
    public AmountWidget(Context context, AttributeSet attrs) {
        this(context);
    }
    
    public AmountWidget(Context context, AttributeSet attrs, int defStyle) {
        this(context);
    }
    

    This will work if you don't care what the attributes or style arguments are, and just want the AmountWidget created the same any time it's inflated.

    0 讨论(0)
  • 2021-01-04 18:42

    Try this:

    mContainerView = (LinearLayout)findViewById(R.id.parentView);    
    LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
    View myView = inflater.inflate(R.layout.row, null);  
    mContainerView.addView(myView); 
    

    mContainerViewis LinearLayout which contain your EditText and row is your xml filename.

    0 讨论(0)
  • 2021-01-04 18:58

    Easiest Solution

    LinearLayout item = (LinearLayout )findViewById(R.id.item);//where you want to add/inflate a view as a child
    
    View child = getLayoutInflater().inflate(R.layout.child, null);//child.xml
    
    item.addView(child);
    
    ImageView Imgitem = (ImageView ) child.findViewById(R.id.item_img);
    
    Imgitem.setOnClick(new ...
    
    0 讨论(0)
提交回复
热议问题