android 中的操作栏图标

actionbar icon in android

我试图在操作栏上添加过滤器图标,我添加了一个名为 filer.xml 的菜单文件,然后我在那个 activity 的 java 文件中扩充了菜单,但是没有用,我在该页面的 xml 布局中看不到我的图标。

filter.xml

      <menu 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"
tools:context=".travels">

<!-- "Mark Favorite", should appear as action button if possible -->
<item
    android:id="@+id/action_filter"
    android:icon="@drawable/ic_sort_black_24dp"
    android:title="@string/bus_filter"
    app:showAsAction="always"/>



 </menu>

travels.java

                      public class travels extends AppCompatActivity implements View.OnClickListener {

    //  private int mYear, mMonth, mDay, mHour, mMinute;
    EditText From_edittext, To_Editext, departure_date_edtxt, return_date_edtxt, time1_edtxt, time2_edtxt;
   private int mYear, mMonth, mDay, mHour, mMinute;
   Button continue_btn;
   Switch switchbtn;
    private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
        new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));

    private static final int PLACE_PICKER_REQUEST1 = 1;
    private static final int PLACE_PICKER_REQUEST2 = 2;



    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_journey);



       @Override
   public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.filter,menu);
    return super.onCreateOptionsMenu(menu);
    /*MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.filter, menu);
    return true;*/

}

}

在菜单项中添加下行 xml;

app:showAsAction="always" 

将此添加到布局文件的根标记 (Menu)。

xmlns:app="http://schemas.android.com/apk/res-auto"

并将其添加到您的按钮

app:showAsAction="always"

您还可以阅读更多相关内容here

放错了onCreateOptionsMenu,应该是这样的

public class travels extends AppCompatActivity implements View.OnClickListener {

 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_journey);
 }

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

就用这个方法..

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.filter,menu);
    return true;

   }