使用Android kotlin 语言,适配Android12 版本,生成一个Fragment,实现滑动水平进度条,改变屏幕亮度
时间: 2023-12-06 07:45:42 浏览: 173
好的,下面是实现的步骤:
1. 在build.gradle文件中添加以下依赖:
```
implementation 'com.google.android.material:material:1.4.0'
```
2. 创建一个新的Fragment类,并在布局文件中添加一个HorizontalSeekBar:
```
class BrightnessFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_brightness, container, false)
val seekBar = view.findViewById<SeekBar>(R.id.seek_bar)
seekBar.max = 255
seekBar.progress = Settings.System.getInt(
requireActivity().contentResolver,
Settings.System.SCREEN_BRIGHTNESS
)
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
val layoutParams = requireActivity().window.attributes
layoutParams.screenBrightness = progress / 255f
requireActivity().window.attributes = layoutParams
Settings.System.putInt(
requireActivity().contentResolver,
Settings.System.SCREEN_BRIGHTNESS,
progress
)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
return view
}
}
```
3. 在布局文件fragment_brightness.xml中添加一个HorizontalSeekBar:
```
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:progressDrawable="@drawable/seekbar_progress"
android:thumb="@drawable/seekbar_thumb"
app:layout_constraintTop_toTopOf="parent" />
```
4. 在drawable文件夹中添加2个xml文件,用于设置SeekBar的样式:
seekbar_progress.xml:
```
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="4dp" />
<solid android:color="#EDEDED" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="4dp" />
<solid android:color="@color/colorPrimary" />
</shape>
</clip>
</item>
</layer-list>
```
seekbar_thumb.xml:
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size android:width="24dp" android:height="24dp" />
<solid android:color="@color/colorPrimary" />
</shape>
```
5. 在MainActivity中将BrightnessFragment添加到ViewPager中:
```
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewPager = findViewById<ViewPager2>(R.id.view_pager)
val adapter = PagerAdapter(this)
adapter.addFragment(BrightnessFragment())
viewPager.adapter = adapter
}
}
```
现在运行应用,你会看到一个水平的SeekBar,通过滑动可以改变屏幕的亮度。
阅读全文