【发布时间】:2014-11-27 16:06:52
【问题描述】:
这是一个简短的问题:
我正在尝试强制操作栏(由工具栏使用)使用 LTR 对齐。我已经成功地使布局本身使用 LTR,但不是“向上”按钮(就像我在 Toolbar 引入之前所做的 here 一样)。
这个视图好像没有ID,我觉得用getChildAt()太冒险了。
谁能帮忙?
答案
这是我发现的一种解决方法,基于 this answer。
我这样做是为了保证它只能找到“向上”按钮,无论它做什么,它都会恢复到之前的状态。
代码如下:
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public boolean onCreateOptionsMenu(final Menu menu)
{
// <= do the normal stuff of action bar menu preparetions
if(VERSION.SDK_INT>=VERSION_CODES.JELLY_BEAN_MR1&&getResources().getConfiguration().getLayoutDirection()==View.LAYOUT_DIRECTION_RTL)
{
final ArrayList<View> outViews=new ArrayList<>();
final CharSequence previousDesc=_toolbar.getNavigationContentDescription();
for(int id=0;;++id)
{
final String uniqueContentDescription=Integer.toString(id);
_toolbar.findViewsWithText(outViews,uniqueContentDescription,View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if(!outViews.isEmpty())
continue;
_toolbar.setNavigationContentDescription(uniqueContentDescription);
_toolbar.findViewsWithText(outViews,uniqueContentDescription,View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if (outViews.isEmpty())
if (BuildConfig.DEBUG)
throw new RuntimeException(
"You should call this function only when the toolbar already has views");
else
break;
outViews.get(0).setRotation(180f);
break;
}
_toolbar.setNavigationContentDescription(previousDesc);
}
//
return super.onCreateOptionsMenu(menu);
}
【问题讨论】:
-
不,getChildAt() 没有风险,只要你涵盖了所有的 egde 案例。
-
但即便如此,我也需要确定这是正确的视图。无论如何,还有其他方法可以实现这一目标吗?
-
您可以使用反射并迭代声明的字段并找到具有您要查找的确切名称的字段(比如说“mNavButtonView”)。这将保证您指向正确的视图。但我不建议使用反射。您宁愿遍历孩子并检查他们的类实例。
标签: android android-actionbar right-to-left android-toolbar