super-sk
super-sk

Reputation: 65

Programmatically add button based on existing layout

According to this post , it is possible to programmatically add button in java.

I would like to build my buttons based on a layout. Is it possible ?

For example,

<!-- btn.xml-->
<Button
    android:id="@+id/button_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="4dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="4dp"
    android:minHeight="60dp"
    android:onClick="myFunction"
    android:textAllCaps="false" />

In my java code, I build buttons over a String list like this :

final LinearLayout layout = findViewById(R.id.my_layout);
for(String label : stringList){
    Log.d("BTN_ITERATION", "for label : " + label);
    Button btn = new Button(getApplicationContext());
    btn.setText(label);
    layout.addView(btn);
}

For each button iteration, I'd like to set a btn.xml layout.

I thought about something like this but I don't know :

button = (button) View.inflate(this, R.layout.btn, null);
layout.addView(button);

Thanks ! ;)

Upvotes: 2

Views: 261

Answers (1)

nulldroid
nulldroid

Reputation: 1230

See this similar question with answer.

Try this:

Button btn = (Button) inflater.inflate(R.layout.btn, layout, false);

Upvotes: 2

Related Questions