一、activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><ImageViewandroid:id="@+id/Lamp"android:layout_width="80dp"android:layout_height="80dp"android:layout_marginTop="100dp"android:visibility="visible"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:srcCompat="@android:drawable/presence_online" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="200dp"android:text="关灯"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/Lamp" /></androidx.constraintlayout.widget.ConstraintLayout>
二、MainActivity.java代码:
package com.example.third;import androidx.appcompat.app.AppCompatActivity;import android.graphics.Color; import android.media.Image; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {ImageView iv1;Button bnt1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bnt1 =findViewById(R.id.button);iv1 = this.findViewById(R.id.Lamp);iv1.setColorFilter(Color.RED);bnt1.setOnClickListener(this);}@Overridepublic void onClick(View view) {if(bnt1.getText().toString().equals("关灯")){bnt1.setText("开灯");iv1.setColorFilter(Color.GRAY);//iv1.setVisibility(View.INVISIBLE);}else if(bnt1.getText().toString().equals(("开灯"))){//iv1.setVisibility(View.VISIBLE);iv1.setColorFilter(Color.RED);bnt1.setText("关灯");}} }
三、AndroidManifest.xml代码:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.Third"tools:targetApi="31"><activityandroid:name=".MainActivity"android:exported="true"android:label="Key control virtual LED"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><meta-dataandroid:name="android.app.lib_name"android:value="" /></activity></application></manifest>
四、运行效果: