【发布时间】:2014-05-21 12:36:44
【问题描述】:
我想显示一个具有自定义布局的操作栏。自定义布局有三个 ImageView,一个在中间,另外两个在操作栏的左右两端。不得有后退按钮或操作项。
这是我用过的:
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
View actionBarView = LayoutInflater.from(this).inflate(resource, null);
actionBar.setCustomView(actionBarView, lp);
自定义布局已正确膨胀,但未占据屏幕的整个宽度。这发生在 Android 4.4.2 (KitKat) 上。在 Gingerbread 上,上述安排可以正常工作。
我在以下讨论中尝试了推荐的解决方案:
- ActionBar - custom view with centered ImageView, Action Items on sides
- RelativeLayout/customview doesn't fill tab's width
但是问题仍然存在。必须有一种方法可以强制布局占据整个屏幕宽度。
我正在使用 V7 AppCompat 库中的操作栏。有谁知道解决这个问题的方法吗??
编辑 1:
这是 XML 布局文件:
<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"
android:orientation="horizontal">
<ImageView
android:id="@+id/left_icon"
android:background="@drawable/leftbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:clickable="true"
android:onClick="leftButtonPressed"
android:hapticFeedbackEnabled="true"
/>
<ImageView
android:id="@+id/center_icon"
android:background="@drawable/centertitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:scaleType="centerInside"
/>
<ImageView
android:id="@+id/right_icon"
android:background="@drawable/rightbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:clickable="true"
android:onClick="rightButtonPressed"
android:hapticFeedbackEnabled="true"
/>
</RelativeLayout>
这是 Gingerbread (2.3.5) 上的样子:
如您所见,它的充气正确。以下是它在 Kitkat (4.4.2) 上的外观:
可以看到右边有一点缝隙,布局没有占满整个宽度。
我不认为布局有问题(它在 Android 2.3.5 上正确充气),但我可能是错的。告诉我我是不是疯了。
编辑 2:
感谢Doctoror Drive 和this post,我能够得到我想要的结果。我知道这有点奇怪:如果您没有任何导航或操作项,为什么要使用操作栏,但这是我的特定问题所需要的。我有一个 TabHost,每个选项卡中都有一堆滑动 Fragments,顶部的 LinearLayout(即 Action Bar)需要在显示不同的 Fragment 时更改其外观。
编辑 3:
这里有更多链接可以进一步理解:
【问题讨论】:
-
发布您的布局文件。
-
除了发布您的布局之外,查看您作为 ActionBar 获得的内容的屏幕截图可能会很有用。
-
请查看编辑。
标签: android android-layout android-actionbar