android studio 添加按鈕點擊事件的三種方法


android studio 添加按鈕點擊事件的三種方法

2018-04-08 16:49:23 bruce135lee 閱讀數 8708

添加按鈕點擊事件

方法一:

1.    在布局中添加一個按鈕,ID為button

2.    在MainActivity.java中的頭文件中添加importandroid.widget.*;

3.    在主類中添加按鈕和其他所需類

TextView textview;
Button button;
4.         在onCreat中添加按鈕監聽函數

5.         button.setOnClickListener(newView.OnClickListener() {
    @Override
    public void onClick(Viewv) {
        String str="點擊事件";
        textview.setText(str);
    }
});

(這個函數在寫完了button.set后都會提示信息)

 

 

方法二:不同按鈕對響應函數不相關時用

1.在content.xml文件中添加一個按鈕,在按鈕屬性中添加

android: onClick = ”button_click”

 

2.在MainActivity.java中的頭文件中添加import android.widget.*;

 

 
3.在主類中添加響應函數public void button_click
public void button1_click(View view)
{
    String str="1";
    textview.setText(str);
}

 

 

 

 
方法三:按鈕較多的時候用,且按鈕與響應有關聯

 

 
1.  在MainActivity.java中的頭文件中添加import android.widget.*;

 

 
2. 在主類中添加按鈕和其他所需類
//Anne add
    TextView textview;
//zhangxu add
    private Button mButton1;
    private Button mButton2;
    private Button mButton3;
    private Button mButton4;

 
3. 在onCreat中給對象賦值
//Anne add
        textview=(TextView)findViewById(R.id.textView);
//zhangxu add
        mButton1 = (Button) findViewById(R.id.button1);
        mButton2 = (Button) findViewById(R.id.button2);
        mButton3 = (Button) findViewById(R.id.button3);
        mButton4 = (Button) findViewById(R.id.button4);

 
4.在onCreat函數中調用監聽函數
 mButton1.setOnClickListener(this);
  mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
此時this標紅,點擊option+回車,選擇第二個選項,令主類重寫

 
5.此時在主類中出現public void onClick(View v) 函數

 
6.在onClick函數中添加執行代碼
switch (v.getId()){
    case R.id.button1:
        str="1";
        textview.setText(str);
        break;
    case R.id.button2:
        str="2";
        textview.setText(str);
        break;
    case R.id.button3:
        str="3";
        textview.setText(str);
        break;
    case R.id.button4:
        str="4";
        textview.setText(str);
        break;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM