12

所以我是android开发的新手......如何创建一个像按钮一样的图像,所以当我按下那个图像时,图像会启动一个特定的活动。所以我希望它显示为图像:

 <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="33dp"
    android:text="Button" />
4

3 回答 3

24

创建 ImageButton 为:

在 main.xml 中:

<ImageButton android:id="@+id/ib"
    android:src="@drawable/bookmark" <-- SET BUTTON IMAGE HERE -->
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

在代码部分:

ImageButton ib=(ImageButton)findViewById(R.id.ib);
ib.setOnClickListener(ibLis);
    }
    private OnClickListener ibLis=new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //START YOUR ACTIVITY HERE AS
             Intent intent = new Intent(YOUR_CURRENT_ACTIVITY.this,NextActivity.class);
             startActivity(intent, 0);
        }
    };

编辑:

第二个选项,如果你想使用按钮视图创建一个类似按钮的图像,然后创建一个自定义按钮:

首先将所有图像(例如按下、聚焦和默认)放在 res/drawable 文件夹中,然后在 drawable/newbtn.xml 中添加 newbtn.xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
    <item android:state_pressed="true"  
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->  
    <item android:state_focused="true"  
          android:drawable="@drawable/button_focused" /> <!-- focused -->  
    <item android:drawable="@drawable/button_normal" /> <!-- default -->  
</selector>

最后在按钮 XML 中设置android:background为:

<Button    
    android:id ="@+id/btn"  
    android:layout_width="wrap_content"   
    android:layout_height="wrap_content"   
    android:text="Hello"  
    android:textColor="#ffffffff"  
    android:background="@drawable/newbtn"   <-- get button background to selector -->
    /> 

请参阅本教程以使用图像创建自定义按钮

在 Android 中创建自定义的精美按钮

于 2012-06-24T10:40:04.940 回答
1

使用 ImageView 元素,将单击侦听器附加到它。

XML:

<ImageView
    android:id="@+id/myImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myPic" 
    />

编码:

ImageView imageView = (ImageView) findViewById(R.id.myImageView);
imageView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(ThisActivity.this, MyOtherActivity.class);
        startActivity(intent);
    }
});

您也可以使用 ImageButton(以相同的方式)。这几乎没有什么区别。您可以在此处查看更多详细信息。可点击的 ImageView 和 ImageButton 的区别

于 2012-06-24T10:37:22.940 回答
0

使用“setOnClickListener()”过于复杂。相反,使用 XML 中的 'onClick' 属性:

<ImageButton
    android:id="@+id/button19"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:onClick="yourCallback"
    android:src="@drawable/your_image"
/>

public void yourCallback(View view) 
{
    ...
}
于 2018-07-04T06:15:33.703 回答