第四课:两种监听器方法(基于AndroidStudio3.2)

一、布局
在主程序界面上添加新按钮,如以前一样。
在这里插入图片描述
创建一个 Activity,名字为MeventActivity
添加一个三个Button控件。
添加调用该窗口程序给按钮“多事件”

   Button btn2 = (Button) findViewById(R.id.button3);
        btn2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent i = new Intent(MainActivity.this , MeventActivity.class);
                //启动
                startActivity(i);
            }
        });

添加向上导航

   <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>

测试ok
在这里插入图片描述

在这里插入图片描述

二、使用内部类作为监听器
我们可以定义另一个嵌套在MeventActivity 中的类,它可以作为我们的
listener对象。 Java允许类嵌套,但需要有些规则。

package com.example.administrator.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MeventActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mevent);

        ButtonHandler bh = new ButtonHandler();
        findViewById(R.id.button4).setOnClickListener(bh);
        findViewById(R.id.button5).setOnClickListener(bh);
        findViewById(R.id.button6).setOnClickListener(bh);
    }


/*
Our inner class as it sits inside MainActivity. We defined it as private because it doesn’t need
to be visible from outside MainActivity. The same as our anonymous class in the previous
sections, this too needs to implement the View.OnClickListenerinterface because we will use it
as the listener for button clicks
 */
    private class ButtonHandler implements View.OnClickListener {
/*
We’re overriding the onClick method of the View.OnClickListener; when any of the three
buttons are clicked, this method gets called, just like in our anonymous class code from previous
sections. The runtime will populate the View parameter with the object reference of the actual
button that was clicked. That is what we’re going to use to identify which button exactly was
clicked using the Android Toast class
*/
        @Override
        public void onClick(View view) {
/*
The getId method of the View object returns an integer value which corresponds to ID of button
as it is defined in the R.class. Remember that layout files are inflated during runtime to produce
the actual Java objects which correspond to View element described in the layout. The runtime
generates the R.class, which we can use to programmatically refer to objects defined in the
layout file
*/
            switch (view.getId()){
                case R.id.button4:
                    show("Button 4");
                    break;
                case R.id.button5:
                    show("Button five");
                    break;
                case R.id.button6:
                    show("Button 6");
                    break;
                default:
                    show("This should not happen");
            }
        }
    }


    void show(String message) {
/*
We are displaying a Toast message. Toast provides a small feedback in the form of a small
popup. It appears as an overlay in the current activity, and the appearance is for a certain
duration only so it doesn’t obscure the current activity. It’s an unobtrusive way to display status
messages
*/
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        Log.i(getClass().getName(), message);
    }

}

Toast是一种很方便的消息提示框,会在 屏幕中显示一个消息提示框,没任何按钮,也不会获得焦点、一段时间过后自动消失!
Toast.makeText(Mainthis, “提示的内容”, Toast.LENGTH_SHORT).show(); 第一个是上下文对象!第二个是显示的内容!第三个是显示的时间,只有LONG和SHORT两种 会生效,即时你定义了其他的值,最后调用的还是这两个!

Android Studio 使用Log
函数原型:Log.w/i/e/d记录日志
其中级别,d(debug) < i(info) < w(warn) < e(error)

测试ok
在这里插入图片描述

三、使用MainActivity作为监听器
处理三个按钮的事件的另一种方法是使用MeventActivity class作为侦听器对象。 定义另一个将作为主要的类程序文件; 这样,它可以与原始主程序并排放在一起项目。
我们将新类命名为MeventActivity2。 它扩展了与原始相同的超类主程序。 将“interfaces”字段留空,并保留默认条目“包”。

  • 在 Project >app >java >com.example.administrator.hello窗口中,右键点击 并选择 New > Java Class。
  • name填MeventActivity2
  • Supreclass填android.support.v7.app.AppCompatActivity
  • interfaces为空
    在这里插入图片描述
    把鼠标放在如上图类中,按Ctrl + O(same keyboard shortcut for Windows, Linux, and macOS).
    在这里插入图片描述
    点ok,出现onCreate方法
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

完整程序

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);
    }


}

测试前需要把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>

</manifest>

运行后直接出现按钮界面

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gumufuyun/article/details/83039729
今日推荐