我正在使用一个拆分操作栏来显示一些简单的媒体控件。见下文:
我使用menuitem.setactionview覆盖快进和快退按钮的默认视图,因为我需要检测用户最初触摸控件的时间(开始快退),然后释放控件(完成快退)。请参见下面的代码:
ImageView rewindButton = new ImageView(getBaseContext());
rewindButton.setId(rewindViewID);
rewindButton.setClickable(true);
rewindButton.setImageResource(R.drawable.ic_action_rewind);
rewindButton.setOnTouchListener(forwardBackwardListener);
MenuItem rewindMenu = menu.findItem(R.id.menu_rewind);
rewindMenu.setActionView(rewindButton);
return true;
这对我来说一切都很好,但却产生了意想不到的副作用。当我触摸快进或快退按钮时,我没有得到默认的蓝色背景(如上面的“向后跳过”控件所示)。它根本不显示背景。我尝试在Ontouch处理程序中设置背景,但是背景并不像默认的那样填充ActionBar的高度(参见下面的示例图片),看起来有一些填充或边距,但是我不知道如何删除它。
我试过以下方法,但没有成功:
手动设置imageview的高度以尝试填充actionbar
从ontouch处理程序返回true或false
有人知道我怎么解决这个问题吗?
最佳答案
我想出了一个解决办法,就是在选定项目时,将所有项目的背景设置为一个小的径向渐变。坡度仍被稍微截断,但几乎不明显。它使定制和常规按钮看起来几乎一样。
首先,我在一个名为res/drawable/radialbackground.xml的文件中创建了径向渐变。请注意,结束颜色是透明的,这对于将渐变淡入空白非常重要,这样它就不会填充整个矩形。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:centerX="0.5"
android:centerY="0.5"
android:endColor="#00FFFFFF"
android:gradientRadius="35"
android:startColor="@color/Gray"
android:type="radial"
/>
</shape>
然后我创建了一个stateListDrawable,名为res/drawable/actionitembackground.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="@android:integer/config_mediumAnimTime" >
<item android:state_pressed="true" android:drawable="@drawable/radialbackground" />
<item android:drawable="@android:color/transparent" />
</selector>
然后我将stateListDrawable分配给我的自定义actionviews的背景:
rewindButton.setBackgroundResource(R.drawable.actionitembackground);
然后我修改了action bar的样式,为常规actionbar项添加了这个新的径向填充。
因此,在values/styles.xml中我添加了:
<style name="Theme.MyTheme" parent="Theme.Sherlock.Light">
<item name="android:selectableItemBackground">@drawable/actionitembackground</item>
<item name="selectableItemBackground">@drawable/actionitembackground</item>
</style>
在我的例子中,基本风格是theme.sherlock.light,但是你可以用你想修改的任何风格来代替它。
然后在androidmanifest.xml中将该样式设置为应用程序的样式
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.MyTheme"
android:uiOptions="splitActionBarWhenNarrow" >
这似乎比试图调试背景被切断的原因更容易。也许改天我会在这上面花更多的时间。
关于android - 使用MenuItem.setActionView在ActionBarSherlock中保留默认的selectableItemBackground,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12926864/