编写Android实战演练的开关灯项目
时间: 2024-01-23 18:44:02 浏览: 35
好的,下面是一个简单的Android实战演练开关灯项目的代码:
首先,需要在XML布局文件中添加一个按钮和一个文本视图。
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.switchlight.MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch Light"
android:onClick="switchLight"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light is Off"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />
</RelativeLayout>
```
在MainActivity.java文件中,我们需要为按钮添加一个点击事件,以控制文本视图的内容。
```java
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
private boolean isLightOn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textview);
}
public void switchLight(View view) {
if(isLightOn) {
textView.setText("Light is Off");
textView.setTextColor(Color.BLACK);
button.setText("Switch Light On");
isLightOn = false;
} else {
textView.setText("Light is On");
textView.setTextColor(Color.YELLOW);
button.setText("Switch Light Off");
isLightOn = true;
}
}
}
```
在这个代码中,我们使用了一个布尔变量isLightOn来记录灯的状态。当按钮被点击时,我们检查isLightOn的值,并根据其值来更改文本视图和按钮的状态。
这个简单的Android实战演练开关灯项目就完成啦!