天天看點

android+3.1.2+imagebutton監聽,3.1Button(示例代碼)

importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.ImageButton;importandroid.widget.Toast;//按鈕的三種方法 優先度 方法1>方法三>方法二 監聽方法>實作方法>xml定義onclick方法

public class MainActivity extends AppCompatActivity implementsView.OnClickListener {privateView view;privateButton button1;privateButton button2;privateButton button3;privateImageButton imageButton;

@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

view= this.findViewById(R.id.mainview);

button1= (Button) this.findViewById(R.id.button1);

button2= (Button) this.findViewById(R.id.button2);

button3= (Button) this.findViewById(R.id.button3);

imageButton= (ImageButton) this.findViewById(R.id.imageButton);

button1.setOnClickListener(this);

button2.setOnClickListener(this);

button3.setOnClickListener(this);

imageButton.setOnClickListener(this);//隻有view有onclicklistener事件

view.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Toast.makeText(MainActivity.this, "view click", 1).show();

}

});//方法1 設定監聽

button1.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Toast.makeText(MainActivity.this, "button1 click", 1).show();

}

});//長按監聽

button1.setOnLongClickListener(newView.OnLongClickListener() {

@Overridepublic booleanonLongClick(View v) {

Toast.makeText(MainActivity.this, "button1 long click", 1).show();return false;

}

});

imageButton.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Toast.makeText(MainActivity.this, "imagebutton click", 1).show();

}

});

}//方法二 響應按鈕點選//xml裡面設定android:onclick裡面方法隻需要名字 不需要括号//1.必須public 2.必須void 3.形參必須隻有一個 而且為View對象

public voidxmlClick(View view) {

Toast.makeText(MainActivity.this, "button2 click", 1).show();

}//方法三//實作OnClickListener接口 重寫onclick方法 控件設定監聽方法setOnClickListener(this)

@Overridepublic voidonClick(View v) {switch(v.getId()) {caseR.id.button1:

Toast.makeText(MainActivity.this, "method 3 button1 click", 1).show();break;caseR.id.button2:

Toast.makeText(MainActivity.this, "method 3 button2 click", 1).show();break;caseR.id.button3:

Toast.makeText(MainActivity.this, "method 3 button3 click", 1).show();break;caseR.id.imageButton:

Toast.makeText(MainActivity.this, "method 3 imagebutton click", 1).show();break;default:

Toast.makeText(MainActivity.this, "others click", 1).show();break;

}

}

}