Android OnClick的四种方法

枕上诗书闲处好,门前风景雨来佳。这篇文章主要讲述Android OnClick的四种方法相关的知识,希望能为你提供帮助。
android OnClick的四种方法
XML文件

< Button android:id="@+id/bt_dial" /> < EditText android:id="@+id/et_number" />

①匿名内部类
java文件
Button bt_dial = (Button) findViewById(R.id.bt_dial);
bt_dial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialPhone();
}
});
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialPhone(); } }); }

②自定义单击事件监听类
{
Button bt_dial = (Button) findViewById(R.id.bt_dial);
bt_dial.setOnClickListener(new MyListener());
}
private class MyListener implements View.OnClickListener {
@Override
public void onClick(View view) {
dialPhone();
}
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_number = (EditText) MainActivity.this.findViewById(R.id.et_number); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(new MyListener()); } private class MyListener implements View.OnClickListener { @Override public void onClick(View view) { dialPhone(); } }

③Activity继承View.OnClickListener
public class MainActivity extends Activity implements View.OnClickListener { EditText et_number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_number = (EditText)MainActivity.this.findViewById(R.id.et_number); Button bt_dial = (Button) findViewById(R.id.bt_dial); bt_dial.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()){ case R.id.bt_dial: dialPhone(); break; default: break; } } }

④在XML文件中显示指定按钮的onClick属性
< Button android:onClick="dialPhoneMethod" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dial_number" android:id="@+id/bt_dial" android:layout_below="@id/et_number" android:layout_alignRight="@id/et_number" android:layout_alignEnd="@id/et_number" />

【Android OnClick的四种方法】在 android:onClick="dialPhoneMethod"处点击Alt+Enter
选择“ create "OnClick(View)” in XXXX",表示在XXXX.java文件中新建点击事件
public void dialPhoneMethod(View view){ dialPhone(); } private void dialPhone() { String number = et_number.getText().toString().trim(); if (TextUtils.isEmpty(number)){ Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + number)); startActivity(intent); }


    推荐阅读