Button,就是按钮,是android中应用最多的组件之一
Button的显示效果图:
本文程序的main.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">
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn1"/>
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn2"/>
</LinearLayout>
本程序的string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="btn1">确认</string>
<string name="btn2">取消</string>
<string name="app_name">Button</string>
</resources>
本程序的java文件
package com.sx.Button;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ButtonActivity extends Activity
{
private Button btn1 = null;
private Button btn2 = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new ButtonClicked());
btn2 = (Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new ButtonClicked());
}
//创建Button监听器
class ButtonClicked implements OnClickListener
{
public void onClick(View v)
{
switch(v.getId())
{
case R.id.btn1:
//系统输出信息
System.out.println("你点击了确定按钮");
//使用Toast类输出信息
Toast.makeText(ButtonActivity.this, "你点击了确定按钮", Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
System.out.println("你点击了取消按钮");
Toast.makeText(ButtonActivity.this, "你点击了取消按钮", Toast.LENGTH_LONG).show();
break;
}
}
}
}