一、onClick属性:
1)、在activity_main.xml中设置button的onClick属性:
<Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开灯"android:onClick="onClick"app:layout_constraintBottom_toTopOf="@+id/textView"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" />
2)、 在MainActivity.java,添加:
public void onclick(View view) {if(buttonled.getText().toString().equals("开灯")){textviewf.setText("灯已开!");buttonled.setText("关灯");}else if(buttonled.getText().toString().equals("关灯")) {buttonled.setText("开灯");textviewf.setText("灯已关!");} }
二、onClickListener
在MainActivity.java,添加:
buttonled.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {if(buttonled.getText().toString().equals("开灯")){textviewf.setText("灯已开!");buttonled.setText("关灯");}else if(buttonled.getText().toString().equals("关灯")) {buttonled.setText("开灯");textviewf.setText("灯已关!");}} });
三、重写onClick:
在MainActivity.java,添加:
buttonled.setOnClickListener(this);
@Override public void onClick(View view) {if(buttonled.getText().toString().equals("开灯")){textviewf.setText("灯已开!");buttonled.setText("关灯");}else if(buttonled.getText().toString().equals("关灯")) {buttonled.setText("开灯");textviewf.setText("灯已关!");} }
四、创建内部类实现onClickListener:
在MainActivity.java,添加:
buttonled.setOnClickListener(new FButton());
private class FButton implements View.OnClickListener{public void onClick(View v){if(buttonled.getText().toString().equals("开灯")){textviewf.setText("灯已开!");buttonled.setText("关灯");}else if(buttonled.getText().toString().equals("关灯")) {buttonled.setText("开灯");textviewf.setText("灯已关!");}} }
五、运行效果图: