犹豫是否要发布这个问题,但尝试了 SOF 和其他站点中可用的所有选项,但无法弄清楚为什么我仍然得到 p>
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
我想将 Spinner 添加到我的 Fragment 的操作栏中。我关注了Adding spinner to ActionBar并查看了与此相关的所有帖子。
我的 fragment 类有这个:
public class MyFragment extends android.support.v4.app.Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
getActivity().getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_reports, menu);
MenuItem item = menu.findItem(R.id.menuReportsSpinner);
SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(getActivity().getActionBar()
.getThemedContext(), R.array.reports_types, android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Item selected from reports : " +position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d(TAG, "No Item selected..");
}
});
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.d(TAG, "Home memu item..");
return true;
}
return super.onOptionsItemSelected(item);
}
}
fragment_layout 有这个:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
menu_reports.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/menuReportsSpinner"
android:title="@string/reports_menu_title"
app:showAsAction="always"
android:actionLayout="@layout/layout_reports_menu" />
</menu>
我在 super.onCreate() 之前的 onCreate() 中调用了 requestFeature()。任何提示都是有帮助的,thnaks!
最佳答案
您在某个 Activity 中显示您的 fragment ,该 Activity 也有一个布局并调用:setContentView
。此错误告诉您应该在 Activity.onCreate
中的 setContentView
之前调用 requestFeature
,而不是 Fragment.onCreate
关于android - 在添加内容之前必须调用 requestedFeature() - 在 Fragment 中的 ActionBar 中实现 Spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048257/