How to add a copy of XML dynamically

后端 未结 4 1244
深忆病人
深忆病人 2021-01-17 06:08

I am making an Android app, and I want to copy some XML code in a Linear Layout, and re-insert it into the Linear Layout so that there are two of the Relative Layouts in the

4条回答
  •  粉色の甜心
    2021-01-17 06:16

    You are probably getting an error message that the View you are trying to add already has a parent. You would need to call removeView() on the parent of your TextViews or removeAllViews() to just remove them all before adding them to your new RelativeLayout. Something like

    m.removeAllViews();
    
    m2.addView(et1);
    m2.addView(et2);
    m2.addView(et3);
    m2.addView(et4);
    

    However, if you are adding them multiple times then you probably want to create new instances of them as you do with your RelativeLayout (m2). Then you can use the params that your original TextViews have. If this isn't your current error then please post your logcat but this will cause an exception.

    Edit

    TextView et1 = (TextView) findViewById(R.id.top1);
    TextView et2 = (TextView) findViewById(R.id.right1);
    TextView et3 = (TextView) findViewById(R.id.left1);
    TextView et4 = (TextView) findViewById(R.id.bottom1);
    
    //Create the new TextViews
    TextView tv1 = new TextView(m.getContext());  //if inside Activity you can use this instead of m.getContext()
    // set params which you can get from the above TextViews
    m2.addView(tv1);
    ...
    

提交回复
热议问题