在工具栏

时间:2016-06-25 13:40:52

标签: android android-search

搜索图标和编辑文本正确显示。早期它在我的应用程序中工作正常,不确定是什么导致这种行为。 在示例应用程序中可以看到相同的行为。

请建议我解决此问题的方法。

enter image description here

MainActivity:

public class MainActivity extends AppCompatActivity {

private Toolbar mToolBar;
private MenuItem searchItem;

private SearchView mSearchView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mToolBar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(mToolBar);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    searchItem = menu.findItem(R.id.action_search);
    mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    setupSearchView(searchItem);

    return true;
}

private void setupSearchView(MenuItem searchItem) {
    mSearchView.setIconifiedByDefault(true);
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.searchwidget.MainActivity">

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_awesome_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material"
    app:title="@string/app_name">

</android.support.v7.widget.Toolbar>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="@+id/activity_main"
    app:layout_constraintLeft_toLeftOf="@+id/activity_main"
    app:layout_constraintRight_toRightOf="@+id/activity_main"
    app:layout_constraintTop_toTopOf="@+id/activity_main" />

menu.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:apk="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_search"
    android:title="search"
    apk:actionViewClass="android.support.v7.widget.SearchView"
    android:icon="@drawable/ic_search_white_24dp"
    apk:showAsAction="always|collapseActionView" />

0 个答案:

没有答案