Android 如何定位和设置工具栏的不同元素?

Android 如何定位和设置工具栏的不同元素?,android,android-toolbar,Android,Android Toolbar,我想创建一个如图所示的工具栏 我们怎么做 我已经这样做了: Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(myToolbar); 到目前为止。通过以下方法创建自定义工具栏: <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:andr

我想创建一个如图所示的工具栏

我们怎么做

我已经这样做了:

 Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(myToolbar);

到目前为止。

通过以下方法创建自定义工具栏:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="@mipmap/top_bar_bg"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    />
把这个放在舱单上

<activity
            android:name=".activity.RegisterActivity"
            android:label="@string/profile"
            android:parentActivityName=".activity.HomeActivity"
            >
将此项放入“活动”菜单:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement


        if(id == R.id.action_settings){
            Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

您应该覆盖OnCreateOptions菜单,如下所示:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_layout_name, menu);
}
其中,menu_layout_name是菜单布局的名称。此菜单\u布局\u名称如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/search"
        android:title="@string/search_item"
        android:icon="@android:drawable/ic_menu_search"/>
</item>

您可以使用这样设计的相对或线性布局。工具栏不是必需的
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_layout_name, menu);
}
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/search"
        android:title="@string/search_item"
        android:icon="@android:drawable/ic_menu_search"/>
</item>