Search code examples
androidandroid-layouttextviewandroid-buttonandroid-imagebutton

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


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


Solution

  • 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