2016-08-23 46 views
0

我想加載一個活動,並立即使用可用的放大鏡單擊/搜索基於輸入的詞彙搜索欄。這是我希望看到的,當我加載活動:在活動負載上實施搜索欄

enter image description here

代碼:

public class FlickRActivity extends AppCompatActivity { 

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

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

    MenuItem searchItem = menu.findItem(R.id.search); 
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); 
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
     @Override 
     public boolean onQueryTextSubmit(String query) { 
      return false; 
     } 

     @Override 
     public boolean onQueryTextChange(String newText) { 
      Toast.makeText(getApplicationContext(),newText,Toast.LENGTH_SHORT).show(); 
      return false; 
     } 
    }); 

    return true; 
    } 

} 

menu.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<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/hint_search" 
    android:icon="@android:drawable/ic_menu_search" 
    app:showAsAction="collapseActionView|ifRoom" 
    app:actionViewClass="android.support.v7.widget.SearchView" /> 
</menu> 

回答

1

只需撥打searchItem.expandActionView();