【问题标题】:How to add image button and label on main button dynamically in android?如何在android中动态地在主按钮上添加图像按钮和标签?
【发布时间】:2017-01-03 06:26:41
【问题描述】:

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

【问题讨论】:

  • 通过扩展 View 创建自定义视图并在画布上绘图。
  • 你能提供一些图形用户界面吗?

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


【解决方案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);
}

如果您遇到任何问题.. 告诉我.. 希望对您有所帮助

【讨论】:

    【解决方案2】:

    好的,首先在 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多