android按钮点击——implements View.OnClickListener

android按钮点击——implements View.OnClickListener

还可以使用如下方式进行button的响应,就是不使用匿名内部类,可以直接让当前类实现OnClickListener接口即可。
下面是代码:
package xueyou.xueyoucto.com.androidviews;


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

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private final String Tag = "MAINACTIVITY";
    public Button button1;
    public Button button2;
    public Button button3;

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

        button1 = (Button) this.findViewById(R.id.button1);
        button2 = (Button) this.findViewById(R.id.button2);
        button3 = (Button) this.findViewById(R.id.button3);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button1:
                Toast.makeText(MainActivity.this, "button1.click", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button2:
                Toast.makeText(MainActivity.this, "button2.click", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                Toast.makeText(MainActivity.this, "button3.click", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}





    

运行结果:
android按钮点击——implements View.OnClickListener_第1张图片

你可能感兴趣的:(Android)