Android笔记

Android 按钮事件两种经典写法

2019-07-23  本文已影响0人  Cedric_h

原文:https://blog.csdn.net/uyy203/article/details/51885401

集中处理

public class MainActivity extends AppCompatActivity {
 
    private MyOnClickListener myOnClickListener;
    private Button button1,button2,button3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        button1=(Button)findViewById(R.id.button1);
        button2=(Button)findViewById(R.id.button2);
        button3=(Button)findViewById(R.id.button3);
        myOnClickListener=new MyOnClickListener();
        myOnClickListener.setContext(getBaseContext());
 
 
        button1.setOnClickListener(myOnClickListener);
        button2.setOnClickListener(myOnClickListener);
        button3.setOnClickListener(myOnClickListener);
 
            }
 
}
 
 
class MyOnClickListener implements View.OnClickListener{
 
    private Context context;
 
    public void onClick(View v){
        switch(v.getId()){
            case  R.id.button1:
                Toast.makeText(context,"button1",Toast.LENGTH_SHORT).show();
                break;
 
            case R.id.button2:
                Toast.makeText(context,"button2",Toast.LENGTH_SHORT).show();
                break;
 
            case R.id.button3:
                Toast.makeText(context,"button3",Toast.LENGTH_SHORT).show();
                break;
        }
    }
 
    public void setContext(Context contex){
        this.context=contex;
    }
 
}

单个处理

public class MainActivity extends AppCompatActivity {
 
    private Button button1, button2, button3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
 
 
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(),"Button1",Toast.LENGTH_SHORT).show();
            }
        });
 
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(),"button2",Toast.LENGTH_SHORT).show();
            }
        });
 
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(),"button3",Toast.LENGTH_SHORT).show();
            }
        });
 
    }
}
上一篇下一篇

猜你喜欢

热点阅读