Creating LinearLayout Programmatically/Dynamically with Multiple Views

前端 未结 4 1241
太阳男子
太阳男子 2020-12-05 09:46

I have a hierarchy that is like this:

  • LinearLayout(horizontal)
    • ImageView
    • LinearLayout(vertical)
      • TextView
      • TextView
4条回答
  •  孤街浪徒
    2020-12-05 10:30

    i suggest you to remove the xml file and just use full code on the java side. you can add the views programatically from the java side. this one from xtreemdeveloper but i change few line for the parent layout.

    // remove this params set it up below
    parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    
    // change the code above into 
    .LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
            addContentView(parent,layoutParams);
    // end of my change
    

    it will look like this in full code =

       LinearLayout parent = new LinearLayout(context);
    
        // remove this params set it up below
        parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    
        // change the code above into 
        .LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
                addContentView(parent,layoutParams);
        // end of my change
    
        parent.setOrientation(LinearLayout.HORIZONTAL);
    
        //children of parent linearlayout
    
        ImageView iv = new ImageView(context);
    
        LinearLayout layout2 = new LinearLayout(context);
    
        layout2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layout2.setOrientation(LinearLayout.VERTICAL);
    
        parent.addView(iv);
        parent.addView(layout2);
    
        //children of layout2 LinearLayout
    
        TextView tv1 = new TextView(context);
        TextView tv2 = new TextView(context);
        TextView tv3 = new TextView(context);
        TextView tv4 = new TextView(context);
    
        layout2.addView(tv1);
        layout2.addView(tv2);
        layout2.addView(tv3);
        layout2.addView(tv4);
    

提交回复
热议问题