Android studio 按键控制虚拟LED

一、activity_main.xml代码:




    

    

二、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;

    @Override
    protected 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);
    }

    @Override
    public 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代码:




    
        
            
                

                
            

            
        
    

四、运行效果:

Android studio 按键控制虚拟LED_第1张图片Android studio 按键控制虚拟LED_第2张图片

你可能感兴趣的:(android,android,studio,android,ide)