我想显示具有自定义布局的操作栏。自定义布局具有三个 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 - 自定义视图,ImageView 居中,操作项位于两侧
- relativelayout/customview 不填充选项卡的宽度
然而问题依然存在。必须有一种方法强制布局占据整个屏幕宽度。
我正在使用 V7 AppCompat 库中的操作栏。有谁知道解决这个问题的方法吗?
EDIT 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 上正确膨胀),但我可能是错的。告诉我我是否疯了。
EDIT 2:
谢谢博士驾驶 and 这个帖子,我能够得到我想要的结果。我知道这有点奇怪:如果您不打算有任何导航或操作项,为什么要使用操作栏,但这正是我解决特定问题所需要的。我有一个TabHost,每个选项卡中都有一堆滑动的Fragments,并且顶部的LinearLayout(即Action Bar)需要在显示不同的Fragment时改变其外观。
EDIT 3:
以下是一些用于进一步了解这一点的链接:
- https://groups.google.com/forum/#!msg/actionbarsherlock/i8JRUkBJjqk/ZzQV9xaM-lkJ
- https://groups.google.com/forum/#!topic/android-developers/FGEi72thLzE