我想增加操作栏的音量。当用户单击该操作时,它应该将 slider 放置在操作栏中以选择正确的音量。
我该怎么做?
最佳答案
处理此问题的最简单方法是使用 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>
现在在您的 Activity
或 Fragment
中实现 SeekBar.OnSeekBarChangeListener
并声明几个变量:
/** 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;
在 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));
要在按下 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));
要控制音量流,请在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);
}
最后在OnSeekBarChangeListener.onStopTrackingTouch
中,删除自定义控件以再次正常显示ActionBar
。
// Remove the SeekBar from the ActionBar
mShowingControls = false;
getActionBar().setDisplayShowCustomEnabled(false);
这是按下 MenuItem
之前和之后的图片。
关于android - 如何将音量 slider 添加到 Android 操作栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101799/