2015年10月23日 星期五

android 有多個按鍵 (button) 時使用switch statement

版面要加入三個 Button (btnRead, btnWrite, btnDel)

MainActivity.java

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


public class MainActivity extends ActionBarActivity {
    private Button btnTxtRead;
    private Button btnTxtWrite;
    private Button btnFileDel;

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

        btnTxtRead = (Button) findViewById(R.id.btnRead);
        btnTxtWrite = (Button) findViewById(R.id.btnWrite);
        btnFileDel = (Button) findViewById(R.id.btnDel);

        btnTxtRead.setOnClickListener(btnListener);
        btnTxtWrite.setOnClickListener(btnListener);
        btnFileDel.setOnClickListener(btnListener);
    }

    private OnClickListener btnListener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnRead:
                        try {
                            Toast.makeText(getApplicationContext(), "Read button pressed", Toast.LENGTH_SHORT).show();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                   case R.id.btnWrite:
                        try {
                            Toast.makeText(getApplicationContext(), "Write button pressed", Toast.LENGTH_SHORT).show();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break 
                case R.id.btnDel:
                        try {
                            Toast.makeText(getApplicationContext(), "Del button pressed", Toast.LENGTH_SHORT).show();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }


            }


        };
    }
 

沒有留言:

張貼留言