How to add a dynamic button to another view?

In android, I have a code block:

// RelativeLayout with id is "root": main.xml
<EditText 
    android:id="@+id/pref_edit_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:hint="Text to share in preference"
/>
// This is the button I want to add to main.xml
 <Button 
    android:id="@+id/save_button"
    android:layout_below="@id/pref_edit_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save"
/>

In my activity, with RelativeLayout.LayoutParam, I can add buttonto a position left, right, top, bottomin a view root, but I cannot add belowor etc ... another view !! So, anyone can give a suggestion to add view, which is dynamically linked to another viewin RelativeLayout?

+5
source share
2 answers

Here you go. This will accomplish what you want to do:

public class ExampleActivity extends Activity {
private RelativeLayout rl;
private EditText editText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_example);

    rl = (RelativeLayout) findViewById(R.id.main_rl);
    editText = (EditText) findViewById(R.id.pref_edit_text);

    Button button = new Button(this);
    button.setText("Save");

    // create the layout params that will be used to define how your
    // button will be displayed
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    // add the rule that places your button below your EditText object
    params.addRule(RelativeLayout.BELOW, editText.getId());

    // set the layoutParams on the button
    button.setLayoutParams(params);

    // add button to your RelativeLayout
    rl.addView(button);
}
}
+7
source

Using

 Button b=new Button(this);

you need to create a new button ... and just add the layout in main.xml using the layout id as

LinearLayout layout=(LinearLayout) findViewById(R.id.linear);

layout.add(R.id.button);

You can easily do this thing to dynamically add a button.

-1
source

All Articles