0

actionbar如何在搜索小部件中触发操作?

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_search:
                finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
4

1 回答 1

3

进行布局搜索并将 EditText 添加到其中。

<EditText
        android:id="@+id/txt_search"
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_action_search"
        />

并且菜单activity_main.xml的那个项目使xml像这样

<item android:id="@+id/ser"
        android:icon="@drawable/ic_action_search"
        android:title="Search"
        android:showAsAction="always" 
        android:actionLayout="@layout/search">

    </item>

在代码中

public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        View v = (View) menu.findItem(R.id.ser).getActionView();
        final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);

        txtSearch.setOnEditorActionListener(new OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
            {
                // TODO Auto-generated method stub
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(txtSearch.getWindowToken(), 0);
                    String mname=v.getText().toString().replaceAll("\\s","");
                    StringBuilder sn=new StringBuilder();
                    sn.append("http://www....");
                    Intent intent=new Intent(getApplicationContext(),Moviesearch.class);

                    final String finurl=sn.toString();
                    intent.putExtra("urlid",finurl);

                    startActivity(intent);

                return false;
            }
        });
        return true;
于 2012-12-23T09:13:33.730 回答