繁体   English   中英

将自定义视图添加到工具栏

[英]Adding custom view to a toolbar

我正在尝试向新工具栏 (Lollipop) 添加自定义视图。 但不知何故,视图被添加到工具栏下方。 当我使用actionBar.setCustomView时它工作正常,但现在迁移到工具栏后,它不起作用。 下面是代码。 应该做哪些改变?

片段:

    toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
    ((ActionBarActivity) getActivity()).setSupportActionBar(toolbar);

    toolbar.setTitle(getString(R.string.app));



    ActionBar actionBar = ((ActionBarActivity) getActivity())
            .getSupportActionBar();

    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 

    LayoutInflater inflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // inflate the view
    final View view = inflater.inflate(R.layout.actionbar_search, null);
    final ImageView searchIcon = (ImageView) view
            .findViewById(R.id.search_icon);
    final ClearableAutoCompleteTextView searchBox = (ClearableAutoCompleteTextView) view
            .findViewById(R.id.search_box);

    // start with the text view hidden in the action bar
    searchBox.setVisibility(View.INVISIBLE);
    searchIcon.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            toggleSearch(false, view);
        }
    });

    searchBox.setOnClearListener(new OnClearListener() {

        @Override
        public void onClear() {
            toggleSearch(true, view);
        }
    });

    searchBox.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {


        }

    });

toolbar.addView(view);              
// actionBar.setCustomView(view); // This worked previously 
//((ActionBarActivity)getActivity()).getSupportActionBar().setCustomView(view); //doesnt work with toolbar

使用工具栏,我设法实现了这样的目标:

setSupportActionBar(toolbar);
View logo = getLayoutInflater().inflate(R.layout.view_logo, null);
toolbar.addView(logo);

或者您也可以将您的视图添加到工具栏 xml,因为它只是一个 ViewGroup。 这样您就可以在布局编辑器中进行预览。 不需要java代码。

对我很有用。

LayoutInflater mInflater=LayoutInflater.from(context);
View mCustomView = mInflater.inflate(R.layout.toolbar_custom_view, null);
toolbar.addView(mCustomView);

只需将要添加的视图作为 inflate 方法的第二个参数传递给工具栏视图; 这样就不需要调用“addView”了:

setSupportActionBar(toolbar);
View logo = getLayoutInflater().inflate(R.layout.view_logo, toolbar);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM