import android.view.View;
import android.widget.Button;
private Button mButton1;
mButton1 =(Button) findViewById(R.id.myButton1);
mButton1.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
mTextView1.setText("Hi, Everyone!!");
}
});
//-----------------------------------------简洁的写法1-----------------------------------------
1.调用:
mButton1.setOnClickListener(myShowProgressBar);
2.实现:
Button.OnClickListener myShowProgressBar = new Button.OnClickListener()
{
public void onClick(View arg0)
{
}
};
//-----------------------------------------简洁的写法2-----------------------------------------
//创建一个按钮监听事件,然后设置每一个按钮的监听事件函数
1.在main.xml布局文件中定义3个按钮.
2.在main.java中添加监听事件的函数
OnClickListener listener;
listener = new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
myOnClick(arg0);
}
};
3.按钮绑定响应事件
findViewById(R.id.Button01).setOnClickListener(listener);
findViewById(R.id.Button02).setOnClickListener(listener);
findViewById(R.id.Button03).setOnClickListener(listener);
findViewById(R.id.Button04).setOnClickListener(listener);
4.监听事件的实现
private void myOnClick(View arg0) {
switch (arg0.getId()) {
case R.id.Button01:
Toast.makeText(this, "11111", Toast.LENGTH_LONG).show();
break;
case R.id.Button02:
Toast.makeText(this, "22222", Toast.LENGTH_LONG).show();
break;
case R.id.Button03:
Toast.makeText(this, "33333", Toast.LENGTH_LONG).show();
break;
case R.id.Button04:
Toast.makeText(this, "44444", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
//-----------------------------------------添加背景的图片-----------------------------------------
1.在drawable中添加两张图片 iconempty.png和iconfull.png
2.在drawable中添加btnstyle.xml文件,文件内容如下
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_pressed="false"
android:drawable="@drawable/iconempty"></item>
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/iconfull"></item>
</selector>
3.在main.xml中定义的Button
<Button android:id="@+id/ImageButton01"
android:background="@drawable/btnstyle"
android:layout_width="128px"
android:layout_height="128px"
android:text="颜色" >
</Button>
//-----------------------------------------让按钮失效-----------------------------------------
mButton1.setEnabled(false);
android Button的应用
最新推荐文章于 2018-08-27 17:47:31 发布