and*_*i g 1 android android-actionbar
我想将音量添加到操作栏.当用户点击该操作时,它应该将滑块放在操作栏中以选择正确的音量我该怎么做
处理此问题的最简单方法是使用ActionBar.setCustomView.
这是一个控制媒体音量的示例:
首先,您需要创建包含您的自定义布局SeekBar.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SeekBar
android:id="@android:id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
现在SeekBar.OnSeekBarChangeListener在你的Activityor中实现Fragment并声明一些变量:
/** Used to actually adjust the volume */
private AudioManager mAudioManager;
/** Used to control the volume for a given stream type */
private SeekBar mVolumeControls;
/** True is the volume controls are showing, false otherwise */
private boolean mShowingControls;
Run Code Online (Sandbox Code Playgroud)
onCreate无论您选择在何处,都可以自定义并将自定义View应用于ActionBar.
// Control the media volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Initialize the AudioManager
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Inflate the custom ActionBar View
final View view = getLayoutInflater().inflate(R.layout.view_action_bar_slider, null);
mVolumeControls = (SeekBar) view.findViewById(android.R.id.progress);
// Set the max range of the SeekBar to the max volume stream type
mVolumeControls.setMax(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
// Bind the OnSeekBarChangeListener
mVolumeControls.setOnSeekBarChangeListener(this);
// Apply the custom View to the ActionBar
getActionBar().setCustomView(view, new ActionBar.LayoutParams(MATCH_PARENT, MATCH_PARENT));
Run Code Online (Sandbox Code Playgroud)
要在MenuItem按下时切换控件,请调用ActionBar.setDisplayShowCustomEnabled并不要忘记将SeekBar进度更新为您正在控制的当前音量级别.
// Toggle the custom View's visibility
mShowingControls = !mShowingControls;
getActionBar().setDisplayShowCustomEnabled(mShowingControls);
// Set the progress to the current volume level of the stream
mVolumeControls.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
Run Code Online (Sandbox Code Playgroud)
在OnSeekBarChangeListener.onProgressChanged通话中控制音量流AudioManager.setStreamVolume
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Adjust the volume for the given stream type
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
}
Run Code Online (Sandbox Code Playgroud)
最后OnSeekBarChangeListener.onStopTrackingTouch,删除自定义控件以ActionBar再次正常显示.
// Remove the SeekBar from the ActionBar
mShowingControls = false;
getActionBar().setDisplayShowCustomEnabled(false);
Run Code Online (Sandbox Code Playgroud)
这是你按下之前和之后的图片MenuItem.

| 归档时间: |
|
| 查看次数: |
2665 次 |
| 最近记录: |