这是一个简短的问题:
我试图强制操作栏(由工具栏使用)使用 LTR 对齐。我已经成功地使布局本身使用 LTR,但没有使用“向上”按钮(正如我在 here 之前所做的那样,在 Toolbar 被引入之前)。
这个 View 似乎没有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);
}
最佳答案
It seems this view doesn't have an ID
你是对的,the navigation view is created programmatically并且从不设置 id。但是您仍然可以使用 View.findViewsWithText
找到它。 .
View.findViewsWithText
带有两个标志:
导航 View 的默认内容描述是"Navigate up" 或者资源 id 是 abc_action_bar_up_description
对于 AppCompat 和 action_bar_up_description
对于框架的,但是您可以使用 Toolbar.setNavigationContentDescription
轻松应用自己的应用程序.
这是一个示例实现:
final Toolbar toolbar = ...;
toolbar.setNavigationContentDescription("up");
setActionBar(toolbar);
final ArrayList<View> outViews = Lists.newArrayList();
toolbar.findViewsWithText(outViews, "up", View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
outViews.get(0).setRotation(180f);
结果
关于android - 如何获取工具栏上使用的 "up"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174754/