<TextView
android:id="@+id/txt_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="光线传感器!" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示" />
<ImageButton
android:id="@+id/img_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/img_1"/>
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager senseormanager;
private TextView txtview;
private Button btn_values;
private ImageView img_view;
LinearLayout alyout;
int i =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtview = findViewById(R.id.txt_view);
btn_values = findViewById(R.id.button);
img_view = findViewById(R.id.img_view);
senseormanager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume(){
super.onResume();
senseormanager.registerListener(this,senseormanager.getDefaultSensor(Sensor.TYPE_LIGHT),SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause(){
super.onPause();
senseormanager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event){
btn_values.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float[] values = event.values;
int sensorType = event.sensor.getType();
StringBuilder stringbuilder = null;
if(sensorType==Sensor.TYPE_LIGHT){
stringbuilder = new StringBuilder();
stringbuilder.append("光的强度值:");
stringbuilder.append(values[0]);
txtview.setText(stringbuilder.toString());
}
if(i==1){
//alyout.setBackgroundResource(R.drawable.img_2);
img_view.setImageResource(R.drawable.img_2);
i *= -1;
}else{
img_view.setImageResource(R.drawable.img_1);
i *= -1;
}
}
});
}
@Override
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
}
11-09
529
04-11