How to add a view programmatically to RelativeLayout?

后端 未结 2 2073
梦谈多话
梦谈多话 2020-12-01 04:03

Can you give me a very simple example of adding child view programmatically to RelativeLayout at a given position?

For example, to reflect the followin

相关标签:
2条回答
  • 2020-12-01 04:45

    Heres an example to get you started, fill in the rest as applicable:

    TextView tv = new TextView(mContext);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    params.leftMargin = 107
    ...
    mRelativeLayout.addView(tv, params);
    

    The docs for RelativeLayout.LayoutParams and the constructors are here

    0 讨论(0)
  • 2020-12-01 05:03

    Firstly, you should give an id to your RelativeLayout let say relativeLayout1.

    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
    TextView mTextView = new TextView(context);
    mTextView.setText("Dynamic TextView");
    mTextView.setId(111);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    mainLayout.addView(mTextView, params);
    
    0 讨论(0)
提交回复
热议问题