带有两个拉伸(stretch)按钮的 Android 操作栏

标签 android button android-actionbar stretched

有人知道如何轻松实现带有两个拉伸(stretch)按钮的操作栏吗?

以下是 Google 日历应用的示例:

enter image description here

谢谢!

最佳答案

如果您出于某种原因宁愿在 ActionBar 中使用它,实现此目的的一种方法是在 Action Bar 上使用自定义 View 。在您自定义 View 的布局中,然后担心设置按钮宽度。

告诉 Activity 为操作栏使用自定义 View :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);   
    final ActionBar ab = getActionBar();
    ab.setDisplayShowHomeEnabled(false);
    ab.setDisplayShowTitleEnabled(false);     
    final LayoutInflater inflater = (LayoutInflater)getSystemService("layout_inflater");
    View view = inflater.inflate(R.layout.action_bar_edit_mode,null); 
    ab.setCustomView(view);
    ab.setDisplayShowCustomEnabled(true);
}

layout/action_bar_edit_mode.xml 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="fill_horizontal"
    android:orientation="horizontal" >
    <LinearLayout 
        android:layout_alignParentLeft="true"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <Button
        android:id="@+id/action_bar_button_cancel"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"           
        android:layout_weight="1"
        android:text="Cancel" />

        <Button
        android:id="@+id/action_bar_button_ok"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"           
        android:layout_weight="1"
        android:text="Ok" />
    </LinearLayout>    
</RelativeLayout>

希望它对某人有所帮助!

注意:我意识到这里的嵌套布局很丑,通常我不会推荐这个,但由于某种原因,actionbar 自己的布局拒绝让 LinearLayout 自己占据整个宽度。通常你应该避免像这样不必要的嵌套布局! 也许如果有人看到这一点,他们可以为我们指出更好的解决方案?

它的样子: result

编辑:有一个 excellent post由 Roman Nurik 撰写,他解释了一种很好地做到这一点的方法。

编辑 2: 如果有人好奇,布置按钮的正确方法是让它们扩展操作栏的宽度而无需像我上面那样嵌套布局,设置具有适当布局参数的自定义 View ,允许其组件匹配父组。

基本上:

actionBar.setCustomView(view,new ActionBar.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT));

关于带有两个拉伸(stretch)按钮的 Android 操作栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264808/

相关文章:

Android Gmail 应用程序不会在 HTML 电子邮件中呈现背景图像

java - 响应Intent。ACTION_BATTERY_CHANGED

javascript - Highcharts 3 之类的菜单按钮不会显示

javascript - 将提示值传递到输入按钮上的 "click"事件触发的函数中

android - 可以在Android Action Bar中通过xml设置ActionViewClass的属性吗?

android - 在 Android 中调整位图大小

android - 如何在 android 中显示我的应用程序的费率对话框

javascript - 提交按钮重新加载页面

Android:如何将 ActionBar "Home"图标更改为应用程序图标以外的其他内容?

android - 如何将溢出菜单添加到工具栏?