android - 在操作栏中填充水平自定义 View

标签 android android-actionbar

我想在我的操作栏上使用完全覆盖操作栏的自定义 View (宽度匹配父级)

But my custom view does not cover the entire width of the action bar.

enter image description here

public class MyActivity extends AppCompatActivity {

    private ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_entry_screen);
        setActionBar();
    }

    private void setActionBar() {
        actionBar = getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        View abView = actionBar.getCustomView();
        LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutParams layout = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        View v = inflator.inflate(R.layout.action_bar, null);
        actionBar.setCustomView(v, layout);
        actionBar.setDisplayShowCustomEnabled(true);
    }

action_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/mvp_logo"
        android:layout_alignParentRight="true" />

</RelativeLayout>

我引用了以下链接:

How to display custom view in ActionBar?

Manually inflating custom view yields different layouts for ActionBar custom view

Android center custom view in actionbar

Android: How to center a component in a custom view in action bar?

谢谢

最佳答案

Toolbar可能对你更好,但请注意,这违反了设计指南,会使你的应用程序不适合 Android 生态系统,该区域通常是找到上下文菜单的地方,大多数用户都会了解这种行为。

您可以通过删除内容插入来修复此行为,如下所示

View myLogo = mInflater.inflate(R.layout.actionbar_custom, null);
getSupportActionBar().setCustomView(myLogo);
((Toolbar) myLogo.getParent()).setContentInsetsAbsolute(0,0);

如果您已经更改为工具栏,您可以在自定义 View 的 XML 中修复它

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

关于android - 在操作栏中填充水平自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31837692/

相关文章:

java - 使用 Assets 文件夹(本地)进行简单的json解析

java - 如何在 onCreate 之后将项目添加到 ActionBarSherlock?

android - 像在 actionBar 中一样创建微调器

当目标 sdk 版本大于 10 时,Android 操作栏菜单不显示。为什么?

android - 带有代码混淆的多模块库

android - LibGDX - InputProcessor - 如果用户将手指从代表在 X 上移动的按钮拖动到代表在 Y 上移动的按钮

android - 使用用户名和密码存储和重新登录的最佳方式是什么?

android - 以编程方式播放 YouTubePlayer 不起作用

android - 操作栏中的向上按钮自定义

java - 首选项屏幕以及半透明的导航和状态栏