点击事件,点击吐司(Toast),匿名内部类实现

1、按钮点击事件

      当点击按钮后出现效果或结果就是点击事件,首先先看效果图,点击后吐司在屏幕上、

        点击事件,点击吐司(Toast),匿名内部类实现_第1张图片

     代码如下:

        xml:

        




    

       Java:

package com.example.zy.mystudy;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.btn);
        button.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, "匿名内部类方式", Toast.LENGTH_SHORT).show();
                    }
                }

        );
    }
}

这样是通过了匿名内部类方式实现了点击按钮吐司

=====================================================================

同时,你也可以这样写:

xml:




    

Java:

package com.example.zy.mystudy;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Button button1;
    private Button button2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button)findViewById(R.id.btn1);
        button1.setOnClickListener(onClickListener);

        button2 = (Button)findViewById(R.id.btn2);
        button2.setOnClickListener(onClickListener);
    }
    View.OnClickListener onClickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn1:
                    Toast.makeText(MainActivity.this,"点击事件1",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.btn2:
                    Toast.makeText(MainActivity.this,"点击事件2",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}

这样写可以避免在创建时多次占用资源

你可能感兴趣的:(Android,Android更上一层楼)