How to add image button and label on main button dynamically in android?

1.5k views Asked by At

I want to create multiple buttons dynamically with label and another small button on it. For example:-
enter image description hereenter image description here

2

There are 2 answers

0
Mayur Raval On BEST ANSWER

Need to add drawable in button right.I think there is no need to add extra button on button if there is no action for upper button . please see below code and try

LinearLayout parent = new LinearLayout(this);

parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0 ; i < 10 ; i++) {
    Button b = new Button(this);
    b.setText("Primary");
    Drawable image = ContextCompat.getDrawable(getApplicationContext(), R.drawable.your_image);
    image.setBounds(0, 0, 60, 60);
    b.setCompoundDrawables(null, null, image, null);
    parent.addView(b);
}

If you face any issue .. let me know.. hope this help

0
Pankaj Lilan On

Ok so first of all make an item of Image button and label in xml.

item.xml

<LinearLayout
    android:id="@+id/llOverallTitleDOWN"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Then on java file refer the below code.

    LinearLayout llOverallTitleDOWN = (LinearLayout) findViewById(R.id.llOverallTitleDOWN);

    View layout2 = LayoutInflater.from(this).inflate(R.layout.item, llOverallTitleDOWN, false);

    ImageButton imgBtn = (ImageButton) layout2.findViewById(R.id.imgBtn);
    TextView textLabel = (TextView) layout2.findViewById(R.id.textLabel);
    imgBtn.setImageBitmap(bitmap);
    textLabel.setText("label");

    llOverallTitleDOWN.addView(layout2);