它很简单,您可以做的是使用拖放在 xml 中创建一个 SeekBar 或编写它的 xml
SeekBar
android:id="@+id/brightnesSseeker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:max="255"
android:progress="255" />
在 mainActivity 类中这样做:
brightnesSseeker = (SeekBar) findViewById(R.id.brightnesSseeker);
brightnesSseeker
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// Nothing handled here
}
public void onStartTrackingTouch(SeekBar seekBar) {
// Nothing handled here
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
// Set the minimal brightness level
// if seek bar is 20 or any value below
if (progress <= 20) {
// Set the brightness to 20
screenBrightness(20);
} else {
// Set brightness variable based on the progress bar
screenBrightness(progress);
}
stobeVariable=progress*10;
}
});
然后写一个简单的函数:
private void screenBrightness(double newBrightnessValue) {
/*
* WindowManager.LayoutParams settings = getWindow().getAttributes();
* settings.screenBrightness = newBrightnessValue;
* getWindow().setAttributes(settings);
*/
WindowManager.LayoutParams lp = getWindow().getAttributes();
float newBrightness = (float) newBrightnessValue;
lp.screenBrightness = newBrightness / (float) 255;
getWindow().setAttributes(lp);
}
在调用 screenBrightness 函数之前还要检查亮度模式,因为有时模式被选择为自动亮度,在这种情况下亮度不会改变。您还需要清单文件中的权限。
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
在 setOnSeekBarChangeListener 之前在 onCreate 中调用下面的函数
void changeBrightnessMode(){
try {
int brightnessMode = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE);
if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
} catch (Exception e) {
// do something useful
}
}