【问题标题】:SearchView Menu Item Not Overriding Custom AppCompatToolbarSearchView 菜单项未覆盖自定义 AppCompatToolbar
【发布时间】:2016-07-17 13:49:55
【问题描述】:

我正在我的 Fragment 的 RecyclerView 上实现 SearchView,如下所示。当用户点击搜索按钮时,我希望 SearchView 的菜单项覆盖工具栏并显示区域供他们搜索。如果我不使用工具栏的自定义样式,它可以正常工作,但是当我这样做时,会得到下面的图像。

这是我目前得到的:

这是 EventListActivity 继承自的类:

public abstract class SingleFragmentActivity extends AppCompatActivity {

    protected abstract Fragment createFragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.eventcalendar_activity_fragment);

        // Manages our fragments. We can call it to add a fragment to an activity in code
        FragmentManager fm = getSupportFragmentManager();
        // Check if fragment of R.id already exits
        // The FragmentManager saves out the list of fragments on rotation destruction or memory reclaim
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);
        // If the the fragment does not exist, create it
        if(fragment == null) {
            fragment = createFragment();
            // Create a new fragment transaction, include one add operation in it, and then commit it
            fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
        }
    }

}

这将创建管理和使用 RecyclerView 的片段:

公共类 EventListActivity 扩展 SingleFragmentActivity {

@Override
protected Fragment createFragment() {

    // Setting arguments for the new fragment created from the intent from EventFeedResultWrapper
    EventListFragment fragment = new EventListFragment();
    fragment.setArguments(getIntent().getExtras());
    return fragment;
}
}

包含 SearchView 将与之交互的 RecyclerView 的片段。这是搜索菜单按钮膨胀的地方。这是我一直在尝试修改工具栏的地方:

public class EventListFragment extends Fragment {

private RecyclerView mEventRecyclerView;
private EventAdapter mAdapter;


// Telling the FragmentManager that it is
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(R.layout.action_bar_center);
        View sabView = ((AppCompatActivity)getActivity()).getSupportActionBar().getCustomView();
        TextView titleTxtView = (TextView) sabView.findViewById(R.id.action_bar_title);
        titleTxtView.setText("Events Calendar");
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(true);

    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.eventcalendar_fragment_event_list, container, false);

     mEventRecyclerView = (RecyclerView) view.findViewById(R.id.event_recycler_view);
     // RecyclerView requires a layout manager to work, layout manager is in charge of position items on screen
     mEventRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    updateUI();

    return view;
}

// Populate the menu instance
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.eventcalendar_menu, menu);
}

// When we edit a EventActivity this saves it back to the EventListActivity
// onResume over onStart because we cannot assume the activity will be stopped
// when another activity is in front of it. If the other activity is transparent
// then the activity might just get paused. If it is paused then onStart() will not be called
// but on resume will be called.
// NOTE: In general onResume() is the safest place to take action to update a fragment's view
@Override
public void onResume() {
    super.onResume();
    updateUI();
}

private void updateUI() {
    // Read in the events saved in to EventFeedResultWrapper by the Async task in ParseEventFeedTask
    EventFeedResultWrapper wrapper = (EventFeedResultWrapper) getArguments().getSerializable(ParseEventFeedTask.EXTRA_RESULTS_LIST);
    // Make sure wrapper is not null, it will NEVER be null
    if(wrapper == null){
        throw new RuntimeException("Error: The wrapper is null!");
    }

    // Get all the events from the wrapper/serializable
    List<Event> events = wrapper.getEventFeedResults();
    // Gets the context that we don't use rofl
    EventCal eventCal = EventCal.get(getActivity());
    // Add all the events we got from the wrapper to our event manager eventCal
    eventCal.addEvents(events);

    // Check to see if the EventAdapter is already setup
    if(mAdapter == null) {
        mAdapter = new EventAdapter(events);
        mEventRecyclerView.setAdapter(mAdapter);
    } else {
        mAdapter.notifyDataSetChanged();
    }


}

//Adapter here - removed code since it doesn't do anything with the toolbar
//RecycleView onClickLister - removed code since it doesn't do anything with the toolbar

}

这是自定义 XML 样式

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical" >
    <TextView
        android:id="@+id/action_bar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="24dp"/>
</LinearLayout>

事件菜单 XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
          android:title="Search"
          app:actionViewClass="android.support.v7.widget.SearchView"
          app:showAsAction="always"/>

</menu>

【问题讨论】:

    标签: android android-fragments menu searchview


    【解决方案1】:

    你错过了android:orientation="vertical"。文本垂直显示。你想要水平的吗?

    哦,nvm,我一开始不明白。问题一定是自定义视图的膨胀,由于某种原因,它似乎将原始视图保留在那里并在其他地方膨胀。给我1s,我会在发现问题时更新答案

    在这里查看:getSupportActionBar().setCustomView(view) does not fill entire actionbar

    类似的问题。第一个和第二个答案

    EDIT2:从 EventListFragment onCreate 中删除代码。你不需要膨胀一个searchView,你可以使用默认的。

    @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu_main, menu);
            super.onCreateOptionsMenu(menu, inflater);
            setOptionsMenu(menu);
        }
    
    public void setOptionsMenu(Menu menu) {                
            MenuItem search = menu.findItem(R.id.search);
    
            SearchView searchView;
            /**
             * Setup the SearchView
             */
            SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    
            final boolean[] modifiedOriginal = {false};
    
            searchView = (SearchView) search.getActionView();
    
            if (searchView != null) {
                searchView.setSearchableInfo(searchManager.getSearchableInfo(((Activity) context).getComponentName()));
    
                MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {
                        ...
                        return true;
                    }
    
                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        ...
                        return true;
                    }
                });
    
                final EditText et = ButterKnife.findById(searchView, android.support.v7.appcompat.R.id.search_src_text);
    
                et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }
    
                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }
    
                    @Override
                    public void afterTextChanged(Editable editable) {
                        String s = editable.toString();
                        if (!s.equals("") && !s.equals(" ")) {
                           ...
                        }
                    }
                });
    
                ButterKnife.findById(searchView, android.support.v7.appcompat.R.id.search_close_btn).setOnClickListener(
                        view -> {
                            ...
                            et.setText("");
                        }
                );
    
            }
        }
    

    您可以保留菜单 xml 原样。

    【讨论】:

    • orientation="vertical" 让我在 ActionBar 中居中显示标题文本。将其设置为“水平”并不能解决问题,而只是将标题左对齐。编辑:我看到你的编辑谢谢。
    • 有什么理由不使用默认的搜索视图?
    • 默认搜索视图?如没有支持库?
    • 设置自定义视图后试试这个:getSupportActionBar().setDisplayShowCustomEnabled(true)
    • 那不起作用...我想知道它是否与 ((AppCompatActivity)getActivity()) 有关,事实上我必须先找到活动才能调整actonbar ...也许这就是菜单无法按预期工作的原因...编辑:也许我会尝试在片段中增加一个新工具栏...
    猜你喜欢
    • 1970-01-01
    • 2016-10-16
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多