actionBar setCustomView不起作用

时间:2015-03-07 14:27:37

标签: android android-actionbar

我想动态更改操作栏的方面。应用我之前创建的自定义视图布局,但仍然无法正常工作。这是我的代码:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setCustomView(R.layout.activity_main);
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    }

        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        ActionBar mActionBar = getSupportActionBar();
        Toast.makeText(this,item.toString(),Toast.LENGTH_LONG).show();
        if(item.toString() == "search"){         
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.search);
        }
        return super.onOptionsItemSelected(item);
    }

自定义布局xml

 <?xml version="1.0" encoding="utf-8" ?>
<LinearLayout 
              xmlns:android="schemas.android.com/apk/res/android" 
              android:orientation="horizontal" 
              android:layout_width="match_parent"
              android:layout_height="match_parent">
  <EditText android:id="@+id/etSearch"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text" />
</LinearLayout>

1 个答案:

答案 0 :(得分:3)

考虑尝试item.toString().equals("search")