Button组件,ImageButton组件,ToggleButton组件
xml文件:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt1"
android:text="按钮1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt2"
android:text="按钮2"
/>
<ImageButton
android:id="@+id/ibt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img3"
android:onClick="myClick"
/>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/toggleButton1"
android:textOn="开始"
android:textOff="停止"
android:onClick="myClick1"
/>
java代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout=(LinearLayout)findViewById(R.id.layout);
Button button1=(Button)findViewById(R.id.bt1);
Button button2=(Button)findViewById(R.id.bt2);
button1.setOnClickListener(listener); //添加监听事件
button2.setOnClickListener(listener);
}
private View.OnClickListener listener=new View.OnClickListener(){ //单独完成监听
public void onClick(View v){
Button btnButton=(Button) v;
switch (btnButton.getId()){
case R.id.bt1:
Toast.makeText(MainActivity.this,"按钮一的单机事件",Toast.LENGTH_SHORT).show();
break;
case R.id.bt2:
Toast.makeText(MainActivity.this,"按钮二的单机事件",Toast.LENGTH_SHORT).show();
break;
}
}
};
public void myClick(View v){ //该方法要求在xml文件中,通过android:onClick属性指定对应的方法名实现
Toast.makeText(MainActivity.this,"图片按钮单机事件",Toast.LENGTH_SHORT).show();
}
public void myClick1(View v){
ToggleButton tbutton1=(ToggleButton) v;
Toast.makeText(MainActivity.this,tbutton1.getText(),Toast.LENGTH_SHORT).show();
}
效果图: