您的位置:首页 > 移动开发 > Android开发

Android 笔记 之 Button

2010-12-30 09:46 190 查看
Button,毋庸置疑,按钮是也。

下面介绍几种给按钮添加监听事件的方法。

1.XML文件。

<?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/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="按钮"
/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮1_OnClick"
android:onClick="button1Clicked"
/>
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮2"
/>
<Button android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="退出"
/>
<Button android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮4"
/>
<Button android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮5"
/>
</LinearLayout>


2.

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
public class ButtonDemo extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//从资源文件中获取按钮对象的引用
Button sButton2 = (Button)findViewById(R.id.button2);
Button sButton3 = (Button)findViewById(R.id.button3);
//注册点击事件监听者
sButton2.setOnClickListener(this);
sButton3.setOnClickListener(this);

Button sButton4 = (Button)findViewById(R.id.button4);
sButton4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(ButtonDemo.this, "button4 is clicked", Toast.LENGTH_LONG).show();
}
});

Button sButton5 = (Button)findViewById(R.id.button5);
sButton5.setOnClickListener(button5ClickedListener);
}

/**
* 按钮响应事件
*/
public void onClick(View aView) {

switch (aView.getId()) {
case R.id.button2:
setTitle("button2 is clicked");
break;
case R.id.button3:
finish();
break;
}
}
public void button1Clicked(View view){
Toast.makeText(ButtonDemo.this, "button1 is clicked", Toast.LENGTH_LONG).show();
}
View.OnClickListener button5ClickedListener = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(ButtonDemo.this, "button5 is clicked", Toast.LENGTH_LONG).show();
}
}
}
};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: