1. 程式人生 > >Android 事件處理簡介

Android 事件處理簡介

一、單擊事件

    public TextView text = null;
    public Button btn = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text= (TextView)super.findViewById(R.id.textView);
        btn = (Button)super.findViewById(R.id.button);
        btn.setOnClickListener(new myClickListener());
    }

    private class myClickListener implements OnClickListener{
        @Override
        public void onClick(View v){
            MainActivity.this.text.setText("Hello");
        }
    }
二、選擇事件
    public TextView text = null;
    public RadioGroup sex=null;
    public RadioButton mail = null;
    public RadioButton femail = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text= (TextView)super.findViewById(R.id.textView);
        sex = (RadioGroup)super.findViewById(R.id.sex);
        mail = (RadioButton)super.findViewById(R.id.mail);
        femail = (RadioButton)super.findViewById(R.id.femail);
        sex.setOnCheckedChangeListener(new myCheckedListener());
    }

    private class myCheckedListener implements OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            String tmp = "";
            if(MainActivity.this.mail.getId() == i)
                tmp = MainActivity.this.mail.getText().toString();
            if(MainActivity.this.femail.getId() == i)
                tmp = MainActivity.this.femail.getText().toString();
            MainActivity.this.text.setText("您選中的性別是:"+tmp);
        }
    }