Java 将文本或图像动态添加到ImageButton
我的布局中有一个ImageButton:Java 将文本或图像动态添加到ImageButton,java,android,android-layout,Java,Android,Android Layout,我的布局中有一个ImageButton: <ImageButton android:id="@+id/grid_item_image" android:layout_width="@dimen/button_main_size" android:layout_height="@dimen/button_main_size" android:gravity="center" android:layout_g
<ImageButton
android:id="@+id/grid_item_image"
android:layout_width="@dimen/button_main_size"
android:layout_height="@dimen/button_main_size"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:padding="10dp"
>
</ImageButton>
我现在不知道是否可能,但我可以动态地将文本或图像添加到此图像按钮吗?我想每次都显示一个图像(
默认图像
),然后,我想在默认图像
中添加一个数字(该数字是可变的),对于图像按钮
您不能设置文本,但可以通过编程方式设置背景可绘制
ImageButton imageButton = (ImageButton) findViewById(R.id.grid_item_image);
imageButton.setBackgroundResource(R.drawable.yourimage);
如果您想同时更改文本和背景图像,最好使用简单的按钮
button.setText("Text");
您无法将文本添加到imagebutton尝试将其替换为Button,我们可以使用
Button.setImageResource()设置文本和图像代码>使用以下代码在imagebutton中动态设置图像:
if (Build.VERSION.SDK_INT >= 16) {
ivcomplete.setBackground(getResources().getDrawable(R.drawable.completed));
}else {
ivcomplete.setBackgroundDrawable(getResources().getDrawable(R.drawable.completed));
}
imagebutton不能包含文本,即,android:text属性未列在imagebutton中。在这种情况下,您可以使用简单的按钮
ImageButton imgbtn = (ImageButton) findViewById(R.id.grid_item_image);
imgbtn.setBackgroundResource(R.drawable.yourimage);
或
首先,您不能向ImageButton添加文本,因为ImageButtons没有任何方法作为setText()和android:text属性
另一种解决方案是,您可以使用按钮而不是ImageButton,并可以查找属性drawableTop或设置复合DrawableSwitthinsBounds(int,int,int,int))
您可以通过以下代码添加图像:
yourImageButton.setBackgroundResource(R.drawable.anyimage);
您只需更改按钮的xml,如下所示:
<Button
android:id="@+id/grid_item_image"
android:layout_height="@dimen/button_main_size"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:drawableLeft="@android:drawable/this_is_your_default_image"
android:text="default text" />
更新的文本
现在将显示默认图像
打开按钮
YOUR | UPDATED
DEFAULT | TEXT
IMAGE | HERE
有一个很好的教程可以在:是的,正如@Sleiman所说,如果你想要文本+图像,你需要使用按钮button.setBackgroundDrawable()
和button.setText()
请参考此链接:在javagrid\u item\u image.setBackgroundResource(R.drawable.some\u image)中试用过吗
但在这种情况下,我会替换所有图像,对吗?如果你不能在上面添加文本,那么你可以创建一个LinearLayout
来代替它,如果你想添加内容,可以创建一个Textview
或ImageView
内部布局,然后我会说使用按钮
这样你就可以使用安卓:drawableLeft=“”
,安卓:drawableRight=“”
,安卓:drawableTop=“”
,安卓:drawableBottom=“”
你可以将图像添加到图像按钮,但文本不能添加到图像按钮。。
button.setText("updated text");
YOUR | UPDATED
DEFAULT | TEXT
IMAGE | HERE