我正在使用ShareActionProvider,但我想自定义图标(我想更改颜色,因为当前它是白色的)。
我正在使用此代码:
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_TEXT, str_share);
mShareActionProvider.setShareIntent(myIntent);
XML:
<item
android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="@string/titlePartager"
android:actionProviderClass="android.widget.ShareActionProvider"
android:icon="@drawable/ic_share"/>
如何更改图标(或颜色)?
谢谢,
编辑/简短答案:如果使用AppCompat的ShareActionProvider,只需actionModeShareDrawable
在主题定义中提供一个新的即可。
<style name="MyTheme" parent="Theme.AppCompat">
<item name="actionModeShareDrawable">@drawable/my_share_drawable</item>
</style>
如果未使用AppCompat,则此资源是为Lollipor或更高版本定义的,但不是为先前版本定义的。
以下是本机的答案ShareActionProvider
(这是此问题的原始范围)。
要更改此图像,您应该更改actionModeShareDrawable
应用程序主题的值。看一下ShareActionProvider
的onCreateActionView()
方法:
public View onCreateActionView() {
// Create the view and set its data model.
...
// Lookup and set the expand action icon.
TypedValue outTypedValue = new TypedValue();
mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
Drawable drawable = mContext.getResources().getDrawable(outTypedValue.resourceId);
...
不幸的是这个属性是不是在Android框架公众(虽然它是如果使用兼容库,如程序兼容性或ActionBarSherlock)。在这种情况下,仅是覆盖该主题的值即可。
如果您都不使用这两个库,则唯一的解决方案(我知道)是创建方法的子类ShareActionProvider
并重新实现该onCreateActionView()
方法。然后,您可以使用所需的任何可绘制对象来代替。
编辑然而,由于onCreateActionView()
使用其他非公共类的实现,这使情况更加复杂。为了避免重复很多代码,您可以通过反射更改图标,如下所示:
public class MyShareActionProvider extends ShareActionProvider
{
private final Context mContext;
public MyShareActionProvider(Context context)
{
super(context);
mContext = context;
}
@Override
public View onCreateActionView()
{
View view = super.onCreateActionView();
if (view != null)
{
try
{
Drawable icon = ... // the drawable you want (you can use mContext to get it from resources)
Method method = view.getClass().getMethod("setExpandActivityOverflowButtonDrawable", Drawable.class);
method.invoke(view, icon);
}
catch (Exception e)
{
Log.e("MyShareActionProvider", "onCreateActionView", e);
}
}
return view;
}
}
与涉及反射的任何解决方案一样,如果ShareActionProvider
将来内部实施更改,这可能会很脆弱。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句