安卓学习之初试事件响应——Button

迈不过友情╰ 2022-05-31 10:25 301阅读 0赞

1.界面布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello"
  11. />
  12. <Button
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="Click me!"
  16. android:id="@+id/btn1"
  17. />
  18. </LinearLayout>

2.事件响应代码(两种),第二种被我注释了

  1. package cn.edu.bit.cs;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.Button;
  7. import android.widget.Toast;
  8. public class UseButtonActivity extends Activity {
  9. private Button btn1=null;
  10. /** Called when the activity is first created. */
  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. btn1=(Button)this.findViewById(R.id.btn1);
  16. //使用独立的事件响应对象
  17. btn1.setOnClickListener(new ButtonClick());
  18. //使用匿名内部类挂接事件响应代码
  19. /*
  20. btn1.setOnClickListener(new View.OnClickListener() {
  21. private int counter=0;
  22. public void onClick(View v) {
  23. Button clickedButton=(Button)v;
  24. counter++;
  25. //在手机上显示短暂的信息
  26. Toast info=Toast.makeText(UseButtonActivity.this, "Button "+v.getId()+" has been clicked "+ counter + " times!", Toast.LENGTH_SHORT);
  27. info.setDuration(1);
  28. info.show();
  29. }
  30. });
  31. */
  32. }
  33. }
  34. class ButtonClick implements OnClickListener{
  35. private int counter=0;
  36. public void onClick(View v) {
  37. counter++;
  38. //在logCat中才能看到输出
  39. System.out.println("I'm clicked "+ counter + " times!");
  40. }
  41. }

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读

    相关 学习Adapter

    Adapter是将数据绑定到UI界面上的桥接类。Adapter负责创建显示每个项目的子View和提供对下层数据的访问。   支持Adapter绑定的UI控件必须扩展Adap