减少 Android 工具栏导航图标的左边距

9

由于我刚接触安卓系统,我在我的工具栏中设置了返回按钮,但是我想减少它左边的填充/边距,我该怎么做?

这是我的设计代码:

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tripidtoolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="name"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold"
/>
<TextView
android:id="@+id/dayNotoolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="#ffffff"
android:layout_marginRight="10dp"
android:text="day"
android:textAllCaps="true"
android:textSize="18sp"
android:textStyle="bold"
/>
</android.support.v7.widget.Toolbar>

这是我手动设置返回按钮的方法。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vouchers_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.arrowbackwhite);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
setSupportActionBar(toolbar);

这是我的屏幕(返回按钮带有左边距


1
可能是重复的问题:Android:从ActionBar的自定义布局中删除左边距 - Evgeniy Mishustin
@EvgeniyMishustin:我尝试了那个问题,但仍然没有解决我的问题... - Ajay Mistry
4个回答

21

将这些行添加到您的工具栏XML中

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

2
将样式设置为工具栏:
<!-- Tool Bar-->
    <style name="ToolbarStyle" parent="@style/Widget.AppCompat.Toolbar">
        <item name="contentInsetStart">0dp</item>
        <item name="android:paddingLeft">0dp</item>
    </style>

在activity的onCreate方法中执行以下操作:
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);

1
为了使其正常工作,您还需要在主题中设置<item name="toolbarStyle">@style/ToolbarStyle</item> - Calin

0
将此代码放入工具栏的XML文件中。
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

4
谢谢您回复。在 XML 编辑器中似乎可以工作,但是当我在真实设备中运行应用程序时,它没有任何变化,仍然像原来一样。您知道为什么会出现这种情况吗? - Ajay Mistry

-3
你可以尝试这样做:
在onCreate方法中:
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);

然后添加这个:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

在你想要返回按钮的清单活动中添加以下内容:

android:parentActivityName=".homeActivity"

这将为您创建返回按钮。


1
我已经创建了返回按钮,但我想减少默认出现在按钮左侧的空间。 - Ajay Mistry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接