安卓学习之初试事件响应——Button
1.界面布局
<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:id="@+id/btn1"
/>
</LinearLayout>
2.事件响应代码(两种),第二种被我注释了
package cn.edu.bit.cs;
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 UseButtonActivity extends Activity {
private Button btn1=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)this.findViewById(R.id.btn1);
//使用独立的事件响应对象
btn1.setOnClickListener(new ButtonClick());
//使用匿名内部类挂接事件响应代码
/*
btn1.setOnClickListener(new View.OnClickListener() {
private int counter=0;
public void onClick(View v) {
Button clickedButton=(Button)v;
counter++;
//在手机上显示短暂的信息
Toast info=Toast.makeText(UseButtonActivity.this, "Button "+v.getId()+" has been clicked "+ counter + " times!", Toast.LENGTH_SHORT);
info.setDuration(1);
info.show();
}
});
*/
}
}
class ButtonClick implements OnClickListener{
private int counter=0;
public void onClick(View v) {
counter++;
//在logCat中才能看到输出
System.out.println("I'm clicked "+ counter + " times!");
}
}
还没有评论,来说两句吧...