如何将图像用作按钮

时间:2011-07-21 14:15:52

标签: android image button

这应该是一个简单的,我真的认为我所做的是正确的,但显然它不是。我有一个我想用作按钮的图像,我创建了按钮并且正在工作。但现在我只想显示这个图像,而不是标准的android“按钮”。

任何人都知道怎么做?

5 个答案:

答案 0 :(得分:22)

使用<selector

在名为drawable-hdpi

button_image.xml文件夹xml文件中创建

并添加以下行:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/picture" /> 
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/picture_pressed" /> 
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/picture_pressed" /> 
    <item android:drawable="@drawable/picture" /> 
</selector>

然后在你的主xml中声明你的按钮添加这一行

android:background="@drawable/button_image"

然后你会得到reall按钮的效果。请注意,您需要两张图片才能获得点击按钮的效果。

如果您不想使用选择器而只使用图片,那么只需

  

机器人:背景= “@绘制/ MYIMAGE”

答案 1 :(得分:9)

使用ImageButton课程。

答案 2 :(得分:6)

您可以使用ImageButtons代替常规按钮

只需在XML中设置图像背景

即可
<ImageButton android:background="@drawable/mypicture"/>

一个很好的教程是Here

答案 3 :(得分:5)

跟我来,你可以在android中使用很多控件来解决这个问题(Button,ImageView,ImageButton,甚至是TextView ......)。只需将图像设置为其背景,然后实现OnClickListener以处理单击事件。

示例,使用ImageView, - 在布局文件中:

      <ImageView
            android:id="@+id/button_login"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="@drawable/button_login"
        />
    后面的代码文件中的
  •     ImageView login;
    login = (ImageView) findViewById(R.id.button_login);
    login.setOnClickListener(new OnClickListener() {
    
        public void onClick(View v) {
            //TODO: your code here
        }
    });
    

答案 4 :(得分:3)

您需要在按钮处将android:background="@drawable/my_pic"写入xml文件。 my_pic是你的pic的名字。希望它可以帮到你。