如何调整Android ActionBar向上按钮(Up button)与屏幕左侧的距离?
黄舟
黄舟 2017-04-17 14:34:30
0
1
221

我想实现这种效果:

这是我的实现代码, 但是返回的箭头处理不好,主要问题, 没法调整箭头与左侧的间隙:

ActionBar bar = getSupportActionBar(); bar.setDisplayShowTitleEnabled(false); bar.setDisplayShowHomeEnabled(true); bar.setDisplayShowCustomEnabled(true); bar.setDisplayHomeAsUpEnabled(true); Resources r = getResources(); Drawable backDrawable = r.getDrawable(R.drawable.arrow_home); bar.setLogo(backDrawable); LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflator.inflate(R.layout.my_booking_actionbar, null); ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); bar.setCustomView(v, layout); Drawable myDrawable = r.getDrawable(R.drawable.list_item_text_selector); bar.setBackgroundDrawable(myDrawable);
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回覆 (1)
Ty80

Update:

可以用 Toolbar 替代 ActionBar:

// Set a Toolbar to act as the ActionBar for this Activity window. setSupportActionBar(android.support.v7.widget.Toolbar toolbar)

如果是在 xml 中定义的 Toolbar,修改属性值为 0 就可以移除 Toolbar 左侧和右侧的空白。



之前的答案:

调用getActionBar().setDisplayHomeAsUpEnabled(true);可以把ActionBar提供的默认的home键(资源Id为android.R.id.home)改成一个左向的小箭头,像这样<,右边紧跟着的依次是app图标、标题。详情参考 Providing Up Navigation

就目前来看,无法改变<与屏幕左侧的距离,我尝试了这样做,无效:

ImageView icon = (ImageView) findViewById(android.R.id.home); if (icon != null) { icon.setPadding(16, 0, 0, 0); }

可行的解决办法是:

(1) 我想到的最直接的办法是重新切一张图,理由如下:
Google官网给出的“左向箭头”的material icon,就包含上下左右间距:
https://www.google.com/design/icons/#ic_...

(2) 看你的代码,你已经为action bar提供了自定义的布局R.layout.my_booking_actionbar,为什么不做的彻底一些呢?放弃使用android提供的Home键android.R.id.home作为UpIndicator。
而是在这个布局中添加一个ImageView,这样就可以自定义你需要的间距离。然后实现ImageView.OnClickListener,点击时返回父activity。

private void initActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(R.layout.actionbar_crime_fragment); View actionView = actionBar.getCustomView(); ImageView upButton = (ImageView) actionView.findViewById(R.id.actionBarUp); upButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Providing Up Navigation,提供了一种返回父Activity的方法, // 同时需要在manifest中增加元数据标签,来定义它的父Activity; // 详情请参考以下链接, // http://developer.android.com/training/implementing-navigation/ancestral.html if (NavUtils.getParentActivityName(CrimePagerActivity.this) != null) { NavUtils.navigateUpFromSameTask(CrimePagerActivity.this); } } }); }

ActionBar的自定义布局文件actionbar_crime_fragment.xml

    

Done.

    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!