Can you give me a very simple example of adding child view programmatically to RelativeLayout
at a given position?
For example, to reflect the following XML:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="107dp" android:layout_marginTop="103dp" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />
I don't understand how to create an appropriate RelativeLayout.LayoutParams
instance.
Below that, the layout_height=0 and layout_weight=1 attributes on the RelativeLayout cause it to take up all the remaining space. You can then center the button in the RelativeLayout . You can play with padding on the button to get it to the size you want.
Android RelativeLayout enables you to specify how child views are positioned relative to each other. The position of each view can be specified as relative to sibling elements or relative to the parent.
Positioning Views RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With