android5.0程序开发之图片按钮ImageButton

android5.0程序开发之图片按钮ImageButton

本文介绍在android5.0程序开发中,图片按钮控件ImageButton的使用方法。

启动eclipse程序,新建一android5.0工程文件ImageButtonDemo。

将图片素材导入争民鉴到drawable目录中,可以复制图片文件,在drawable目录中进行粘贴。注意图片文件名不能以数字开头,否则出错。

在activity_main.xml文件中加入一个TextView文本控件和两个ImageButton图片按钮控件。

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:id="@+id/TextView01"

android:layout_width="wrap_content"

android:layout_height="wrap_content">召侮

android:id="@+id/ImageButton01"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@drawable/a">

android:id="@+id/ImageButton02"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@drawable/c">

再双击打开MainActivity.java文件,导入TextView控件类、ImageButton控件类声明。

import android.widget.TextView;

import android.widget.ImageButton;

在程序中加入文本控件和两个ImageButton控件的引用代码。

final TextView textview1=(TextView)findViewById(R.id.TextView01);

final ImageButton imagebutton1=(ImageButton)findViewById(R.id.ImageButton01);

final ImageButton imagebutton2=(ImageButton)findViewById(R.id.ImageButton02);

分别添加imagebutton1和imagebutton2的执行代码。点击图片按钮会改变按钮。

imagebutton1.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {

textview1.setText("点击了第一个图片按钮");

imagebutton1.setImageDrawable(getResources().getDrawable(R.drawable.b));

imagebutton2.setImageDrawable(getResources().getDrawable(R.drawable.c));

}

});

imagebutton2.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {

textview1.setText("点击了第二个图片按钮");

imagebutton2.setImageDrawable(getResources().getDrawable(R.drawable.d));

imagebutton1.setImageDrawable(getResources().getDrawable(R.drawable.a));

}

});

运行程序,分别点击ImageButton1和ImageButton2,可见如下效果: