活动开始后激活ActionBar搜索

时间:2016-01-25 07:07:19

标签: android android-actionbar

我正在this tutorial之后创建自定义Android ActionBar搜索。

handleMenuSearch();已激活onOptionsItemSelected

protected void handleMenuSearch(){
    ActionBar action = getSupportActionBar(); //get the actionbar

    if(isSearchOpened){ //test if the search is open

        action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
        action.setDisplayShowTitleEnabled(true); //show the title in the action bar

        //hides the keyboard
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);

        //add the search icon in the action bar
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.search));

        isSearchOpened = false;
    } else { //open the search entry

        action.setDisplayShowCustomEnabled(true); //enable it to display a
        // custom view in the action bar.
        action.setCustomView(R.layout.search_bar);//add the custom view
        action.setDisplayShowTitleEnabled(false); //hide the title

        edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor

        edtSeach.requestFocus();

        edtSeach.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loadData(edtSeach.getText().toString());
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            public void afterTextChanged(Editable s) {

            }
        });

        //open the keyboard focused in the edtSearch
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);


        //add the close icon
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.ximage));

        isSearchOpened = true;
    }
}

我想要实现的是在活动开始后激活搜索。

我尝试将handleMenuSearch();放在onCreate下,但这会给我NullPointerException

我想这是因为我无法从mSearchAction拨打onCreate

public boolean onPrepareOptionsMenu(Menu menu) {
        mSearchAction = menu.findItem(R.id.search);
        return super.onPrepareOptionsMenu(menu);
    }

1 个答案:

答案 0 :(得分:0)

使用Handler解决了问题。

protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                handleMenuSearch();
            }
        }, 1000);
    }