Ali*_*aka 17 android android-actionbar
我知道如何在样式xml文件中更改homeAsUpIndicator.问题是如何以编程方式更改它.
我想这样做的原因是因为在某些视图中我支持侧面导航(滑动菜单) - 按向上/向后标题按钮,显示侧面菜单.
在其他视图中,我支持自然向上/向后按钮.
因此,我想用不同的指示器图标来指示两种不同的逻辑 - 侧导航与上/后.
请不要争论这样做的动机.这是给定的状态.谢谢.
Mat*_*ers 21
int upId = Resources.getSystem().getIdentifier("up", "id", "android");
if (upId > 0) {
ImageView up = (ImageView) findViewById(upId);
up.setImageResource(R.drawable.ic_drawer_indicator);
}
Run Code Online (Sandbox Code Playgroud)
Lal*_*h B 15
@matthias的解决方案不适用于所有设备,更改的方法homeAsUpIndicator是在样式中设置@null并以编程方式更改徽标资源.
下面是我在style.xml中的代码
<style name="Theme.HomeScreen" parent="AppBaseTheme">
<item name="displayOptions">showHome|useLogo</item>
<item name="homeAsUpIndicator">@null</item>
<item name="android:homeAsUpIndicator">@null</item>
</style>
Run Code Online (Sandbox Code Playgroud)
在代码中,您可以使用setLogo()方法更改徽标.
getSupportActionBar().setLogo(R.drawable.abc_ic_ab_back_holo_light); //for ActionBarCompat
getActionBar().setLogo(R.drawable.abc_ic_ab_back_holo_light); //for default actionbar for post 3.0 devices
Run Code Online (Sandbox Code Playgroud)
另请注意,Android API 18有以编程方式编辑homeAsUpIndicator的方法,请参阅文档.
这对我有用
getSupportActionBar().setHomeAsUpIndicator(R.drawable.my_home_as_up)
Run Code Online (Sandbox Code Playgroud)
虽然这个答案可能会达到预期的行为,但正如您可以在下面的评论中看到的那样:" 这个hack在某些设备上不起作用 ".我根据Adneal的回答找到了另一种方法,它给了我线索,特别是正确的方法.
较低的API:使用id R.id.up来检索相关的ImageView.
API> = 14:获得相对Parent首页ImageView(android.R.id.home)和检索的第一个孩子也就是UpIndicator(android.R.id.up).
然后,此代码段代码动态更改UpIndicator:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// get the parent view of home (app icon) imageview
ViewGroup home = (ViewGroup) findViewById(android.R.id.home).getParent();
// get the first child (up imageview)
( (ImageView) home.getChildAt(0) )
// change the icon according to your needs
.setImageDrawable(getResources().getDrawable(R.drawable.custom_icon_up));
} else {
// get the up imageview directly with R.id.up
( (ImageView) findViewById(R.id.up) )
.setImageDrawable(getResources().getDrawable(R.drawable.custom_icon_up));
}
Run Code Online (Sandbox Code Playgroud)
我没有在多个设备上进行测试(这就是为什么我不确定上面的代码适用于所有设备的原因),但是这似乎在这里的更新部分中提到的 API中工作得很好.
注意:如果您没有区分较高和较低的API,则会得到NullPointerException,因为R.id.up在较高的API android.R.id.up中不可用,而在较低的API中不可用.
| 归档时间: |
|
| 查看次数: |
18104 次 |
| 最近记录: |