为视图注册事件

作者:追风剑情 发布于:2015-7-26 17:23 分类:Android

视图

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical"
  6. tools:context="${relativePackage}.${activityClass}" >
  7.  
  8. <TextView
  9. android:layout_width="214dp"
  10. android:layout_height="wrap_content"
  11. android:text="Your Name" />
  12. <EditText
  13. android:id="@+id/txt1"
  14. android:layout_width="214dp"
  15. android:layout_height="wrap_content"/>
  16. <Button
  17. android:id="@+id/btn1"
  18. android:layout_width="106dp"
  19. android:layout_height="wrap_content"
  20. android:text="OK"/>
  21. <Button
  22. android:id="@+id/btn2"
  23. android:layout_width="106dp"
  24. android:layout_height="wrap_content"
  25. android:text="Cancel"/>
  26. </LinearLayout>

代码

  1. package com.example.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.Toast;
  10.  
  11. public class UIActivityActivity extends Activity {
  12.  
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_uiactivity);
  17. Button btn1 = (Button)findViewById(R.id.btn1);
  18. btn1.setOnClickListener(btnListener);
  19. Button btn2 = (Button)findViewById(R.id.btn2);
  20. btn2.setOnClickListener(btnListener);
  21. EditText txt1 = (EditText)findViewById(R.id.txt1);
  22. txt1.setOnFocusChangeListener(new View.OnFocusChangeListener() {//匿名内部类
  23. @Override
  24. public void onFocusChange(View v, boolean hasFocus) {
  25. Toast.makeText(getBaseContext(), ((EditText) v).getId()+" has focus - "+hasFocus, Toast.LENGTH_LONG).show();
  26. }
  27. });
  28. }
  29. //创建一个匿名类
  30. private OnClickListener btnListener = new OnClickListener()
  31. {
  32. public void onClick(View v)
  33. {
  34. Toast.makeText(getBaseContext(), ((Button) v).getText(), Toast.LENGTH_LONG).show();
  35. }
  36. };
  37. }

运行效果

111111111.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号