有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Android上对齐操作栏中的中心项

我得到了一个有3个菜单项的动作栏,不幸的是,这些菜单项在左边对齐,而我应该在中间对齐。我一直在四处寻找,尝试了一些东西,但没有任何效果

以下是我目前的代码:

public class Layout extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actionbar);
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(R.layout.actionbar);

}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.action_refresh:
            Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        // action with ID action_settings was selected
        case R.id.action_settings:
            Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }

    return true;
}

}

这是我的右布局图。行动:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:orientation="vertical" >

<TextView
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:layout_gravity="center"
    安卓:text="my Title"
    安卓:textColor="#ffffff"
    安卓:id="@+id/mytext"
    安卓:textSize="18sp"
    安卓:gravity="center"
    />


共 (2) 个答案

  1. # 1 楼答案

    问题是,您实际上不应该将ActionBar(或工具栏,取决于您使用的是哪种工具栏)中的文本居中对齐,这就是为什么这样做并不简单的原因

    如果您让它像当前一样对齐,它应该与72dp键线对齐(这将符合一般材料指南)

    您可以在这里找到这些规范:https://www.google.com/design/spec/layout/structure.html#structure-app-bar(但是,如果您什么都不做,一切都应该正常工作)

  2. # 2 楼答案

    请参阅,您可能已经看到一些应用程序在操作栏(工具栏)上以文本为中心,但布局必须是自定义的,或者API应该是>;5.0来实现这种场景