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

时间:2017-01-03 06:26:41

标签: android android-layout textview android-button android-imagebutton

我想用标签和另一个小按钮动态创建多个按钮。例如: -
enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

需要在按钮右侧添加drawable。我认为如果上按钮没有动作,则无需在按钮上添加额外按钮。请参阅以下代码并尝试

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

如果您遇到任何问题,请告诉我..希望此帮助

答案 1 :(得分:0)

好的,首先在xml中创建一个Image按钮和标签项。

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