android5.0程序开发之图片按钮ImageButton
1、启动eclipse程序,新建一android5.0工程文件ImageButtonDemo。
2、将图片素材导入到drawable目录中,可以复制图片文件,在drawable目录中进行粘贴。注意图片文件名不能以数字开头,否则出错。
3、在activity_main.xml文件中加入一个TextView文本控件和两个ImageButton图片按钮控件。<患修校楷?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> <ImageButton android:id="@+id/ImageButton01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/a"> </ImageButton> <ImageButton android:id="@+id/ImageButton02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/c"> </ImageButton></LinearLayout>
4、再双击打开MainActivity.java文件,导入TextView控件类、ImageButton控件类声明。import android.widget.TextView;import android.widget.ImageButton;
5、在程序中加入文本控件和两个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);
6、分别添加imagebutton1和imagebutton2的执行代码。点击图片按钮会改变按钮。imagebutton1.setOnClick讣嘬铮篌Listener(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)); } });
7、运行程序,分别点击ImageButton1和ImageButton2,可见如下效果: