标签:
法一:匿名内部类
public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { button = (Button) findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "匿名内部类 监听", Toast.LENGTH_SHORT).show(); } }); } }
法二:内部类
public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { button = (Button) findViewById(R.id.btn); button.setOnClickListener(new MyClickListener()); } class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "内部类 监听", Toast.LENGTH_SHORT).show(); } } }
法三:Activity 实现 View.OnClickListener 接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { button = (Button) findViewById(R.id.btn); button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn: Toast.makeText(MainActivity.this, "Activity 实现 View.OnClickListener 接口", Toast.LENGTH_SHORT).show(); break; default: break; } } }
法四:xml 文件中使用 onClick 属性
在 xml 文件中显式指定标签的 onClick 属性,在 Activity 中写一个 onClick 属性同名方法
activity_main.xml
<Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="xmlOnClick" android:text="click" />
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void xmlOnClick(View view) { switch (view.getId()) { case R.id.btn: Toast.makeText(MainActivity.this, "在 xml 文件中使用 onClick 属性", Toast.LENGTH_SHORT).show(); break; default: break; } } }
标签:
原文地址:http://www.cnblogs.com/aegealee/p/5946722.html