android 如何在主按钮上动态添加图像按钮和标签?

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

我想动态创建多个带有标签和另一个小按钮的按钮。例如:-

需要在button中添加drawable right.I认为如果没有upper button的动作就没有必要在button上添加额外的button。请看下面的代码并尝试

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);
}

如果您遇到任何问题..让我知道..希望这对您有所帮助

好的,所以首先在 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>

然后在java文件中参考下面的代码。

    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);