1.在資料夾res->menu->main.xml修改
2.在資料夾res->layout->建立search_layout.xml 一個編輯,一個按鈕
3.MainActivity.java修改
private EditText searchName; private String searchObject; private Button searchButton;
// ================================================================================ // Action Button 建立及點選事件 // ================================================================================ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); View v = (View) menu.findItem(R.id.action_search).getActionView(); //文字編輯部分 searchName = (EditText) v.findViewById(R.id.search); searchName.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub try { searchObject = searchName.getText().toString(); // 取得輸入文字 } catch (Exception e) { } } }); //送出部分 searchButton = (Button) v.findViewById(R.id.searchGo); searchButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub goSearch(); //要做甚麼 } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // home if (drawerToggle.onOptionsItemSelected(item)) { return true; } // action buttons switch (item.getItemId()) { //用不到,刪掉 default: break; } return super.onOptionsItemSelected(item); } void goSearch() { if (searchObject == null) { //搜尋空值,不做事 } else { Intent intent = new Intent(this, xxxx.class); //前進至xxxx頁面 intent.putExtra("searchName", searchObject); //傳值 startActivity(intent); //啟動出發 } }
參考來源:http://blog.stylingandroid.com/basic-actionbar-part5/
http://wptrafficanalyzer.in/blog/adding-custom-action-view-to-action-bar-in-android/