【问题标题】:android.R.id.home throws null pointer exceptionandroid.R.id.home 抛出空指针异常
【发布时间】:2020-08-10 23:49:04
【问题描述】:

我使用 setDisplayHomeAsUpEnabled(true) 来显示主页图标。这工作正常,但它需要很多余量,我试图通过使用下面的代码来重置 -

ImageView view = findViewById(android.R.id.home);
view.setPadding(7,0,0,0);

但它返回空指针异常。

启用主页图标的代码 -

final LayoutInflater actionBarInflater = (LayoutInflater) 
    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewActionBar = actionBarInflater.inflate(R.layout.action_bar, null);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

Image shows the home up icon and my app icon, i want to reduce the space between theme

感谢任何帮助。谢谢!

【问题讨论】:

  • @hafiza 我不确定我是否遗漏了什么,但两者看起来无关。
  • 该 ID 不是 View ID,这就是 findViewById() 找不到它的原因。如果设置得当,该特定按钮可以充当 MenuItem 的 ID。在代码中获取对该按钮的引用可能不值得麻烦。您应该能够使用 XML 属性调整该差距。我相信那会是contentInsetStartWithNavigation,就像this answer 中提到的那样。
  • 感谢 Mike,它提供了帮助,但与 WhatsApp 不同,仍有一些空间。我认为 WhatsApp 所做的是使用一些自定义工具栏,这解释了为什么即使您单击向上图标旁边的图像,它也会带您返回而不是显示朋友的个人资料,并且您实际上需要单击朋友/群组名称才能查看详细信息。感谢您的快速帮助。
  • 嗯,唯一的其他间距将来自该按钮的宽度,因为它比图标宽。如果您想尝试一下,可以使用my answer here 作为指导。它显示了如何设置该按钮的样式。在这种情况下,您需要一个 <item name="android:minWidth">??dp</item> 而不是那里的 tint。我相信,默认值是56dp,所以你绝对可以让它更薄。不过,正如您所指出的,完全自定义的 Toolbar 可能更容易根据需要进行操作。

标签: android android-actionbar toolbar


【解决方案1】:

要访问主页按钮,请参阅my answer。但它不会帮助您从中删除多余的填充和边距。为此,您应该在工具栏布局 xml 中重置它:

     <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="@dimen/actionbar_size"
            android:contentInsetLeft="0dp"
            android:contentInsetStart="0dp"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            android:contentInsetRight="0dp"
            android:contentInsetEnd="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetEnd="0dp"
            app:contentInsetStartWithNavigation="0dp"
            android:padding="0px"
            android:clipToPadding="false">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多