兩種監聽器方法(基於AndroidStudio3.2)
package com.example.administrator.hello;
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Toast;
public class MeventActivity2 extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mevent);
findViewById(R.id.button4).setOnClickListener(this); findViewById(R.id.button5).setOnClickListener(this); findViewById(R.id.button6).setOnClickListener(this); }
@Override public void onClick(View view) { switch (view.getId()){ case R.id.button4: show("Button One 1"); break; case R.id.button5: show("Button Two 2"); break; case R.id.button6: show("Button Three 3"); break; default: show("This should not happen ?"); } } void show(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); Log.i(getClass().getName(), message); }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 測試前需要把App ➤ manifests ➤ AndroidManifest.xml. 改為
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.hello">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MeventActivity2"> <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DisplayMessageActivity" android:parentActivityName=".MainActivity">
<!-- The meta-data tag is required if you support API level 15 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> <activity android:name=".JingcActivity" android:parentActivityName=".MainActivity">
<!-- The meta-data tag is required if you support API level 15 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> <activity android:name=".MeventActivity" android:parentActivityName=".MainActivity"> <!-- The meta-data tag is required if you support API level 15 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> </application>