How to Programmatically Add Views to Views

后端 未结 7 668
春和景丽
春和景丽 2020-11-22 12:55

Let\'s say I have a LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I\'m not asking how it\'s done

7条回答
  •  情话喂你
    2020-11-22 13:37

    This is late but this may help someone :) :) For adding the view programmatically try like

    LinearLayout rlmain = new LinearLayout(this);      
    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);          
    LinearLayout   ll1 = new LinearLayout (this);
    
    ImageView iv = new ImageView(this);
    iv.setImageResource(R.drawable.logo);              
    LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    
    iv.setLayoutParams(lp);
    ll1.addView(iv);
    rlmain.addView(ll1);              
    setContentView(rlmain, llp);
    

    This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)

提交回复
热议问题