把需要的图片按钮放到项目res文件夹下的drawable-hdpi文件夹里。添加ImageButton按钮
.xml文件代码如下
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="35dp"
android:layout_marginTop="126dp"
android:src="@drawable/naoz" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageButton1"
android:layout_below="@+id/imageButton1"
android:src="@drawable/share" />
</RelativeLayout>
<pre name="code" class="java">package com.example.android_button;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class ImageButtons extends Activity implements OnClickListener{
private ImageButton imagebtn1,imagebtn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.imagebuttons);//每次创建完XML,再写对应的类的时候,这句话不要忘记,否则会闪退
imagebtn1=(ImageButton) this.findViewById(R.id.imageButton1);
imagebtn2=(ImageButton) this.findViewById(R.id.imageButton2);
imagebtn1.setOnClickListener(this);
imagebtn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
Toast.makeText(ImageButtons.this, "i am a clock", 1).show();
break;
case R.id.imageButton2:
Toast.makeText(ImageButtons.this, "i am a share", 1).show();
break;
}
}
}
//运行效果图如下