具有背景、源和文本的 Android ImageButton

标签 android xml android-layout imagebutton android-imagebutton

我想创建带有自定义背景、自定义图标和图标下方文本的 ImageButton

我目前的情况是

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="140dp"
    android:layout_height="120dp"
    android:layout_marginLeft="3dp"
    android:layout_marginBottom="6dp"
    android:background="@drawable/btn_rectangle_background"
    android:src="@drawable/ic_action_search"
/>

但是,如果我将 android:text="blablabla" 放在那里,它不会显示 :/

ic_action_homework 是.PNG 图标,而btn_rectangle_background 是XML 文件,它定义了形状

这就是我想要实现的目标 enter image description here

最佳答案

第一个答案:

必须是像这里这样的布局结构:

<LinearLayout
   android:widht_layout="80dp"
   android:height_layout="80dp"
   android:padding="10dp"
   android:gravity="center"
   android:layout_gravity="center"
   android:bacgkground="your_color ARGB"
   >
    <ImageView />
    <TextView />
</LinearLayout>

或第二个答案:

创建自定义 View

public class customView extends View{
   public customView(Context context){
       super(context);
   }
   public customView(Context context, String s, Drawable d){
       super(context);

       // Set Width&Height for this view
       this.measure(80,80);
       // or layout params with specified height&width for this view
       Resources r = getResources();
       int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, **Your width**,
            r.getDisplayMetrics());
       int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, **your height**,
            r.getDisplayMetrics());
       ViewGroup.LayoutParams pp = new ViewGroup.LayoutParams(width,height);
       this.setLayoutParams(pp);


       TextView _text = new TextView(context);
       ImageView _image = new ImageView(context);
       _text.setText(s);
       _image.setBackground(d);
       this.addView(_image);       
       this.addView(_text);

   }
   public customView(Context context, String s, Bitmap b){
     ....
     _image.setImageBitmap(b);
     ...
   }  
}

还将 View 添加到 Root View 中 #id=content of layout from activity:

findByView(R.id.content).addView(new customView((Context)this,"Your Text",getResources().getDrawable(R.drawable.icon));

或按路径使用参数位图:

findByView(R.id.content).addView(new customView((Context)this,"Your Text",BitmapFactory.decodeFile("/sdcard/file.png"));

关于具有背景、源和文本的 Android ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23971334/

相关文章:

android - 如何一个接一个地播放音频文件

android - 如何从 php webservice 在 android 应用程序 arraylist 中解析

java - Android java ImageButton 方法帮助

android - 我如何以编程方式启用和禁用 GPS

xml - 将SQLite数据库转换为XML

java - 即使我使用 NestedScrollView,ToolBar 也无法彻底滚出屏幕

php - 如何使用 LOAD XML LOCAL INFILE 将数据从 xml 插入到 mysql

android - 如何在 Android 的 GridView 中集中最后一个不均匀的行?

安卓多屏设计

安卓 | RecyclerView 不起作用