我需要在对话框中放置一个回收者视图,所以我这样做:
public class RecyclerTemperatureFragment extends DialogFragment
{
String[] items = {getString(R.string.kt),getString(R.string.mph),getString(R.string.kmh)};
RecyclerView recyclerView;
RecyclerTemperatureAdapter adapter;
public static RecyclerTemperatureFragment newInstance()
{
Bundle args = new Bundle();
RecyclerTemperatureFragment fragment = new RecyclerTemperatureFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog dialog = new Dialog(getActivity());
return dialog;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_recycler_temperature, container, false);
recyclerView = (RecyclerView)rootView.findViewById(R.id.recTemperature);
adapter = new RecyclerTemperatureAdapter(getActivity(),items);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
recyclerView.setAdapter(adapter);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return rootView;
}
}
在我的班级的OnClickListener事件中,我这样做:
public class TrueAirSpeedFragment extends Fragment
{
TextView casTW, paTW, satTW, ins, clc,casUM,paUM,satUM;
ImageView calculate;
EditText casET, paET, satET;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//this works
}
private void setUpCASUM(final TextView textview)
{
RecyclerTemperatureFragment dialog = RecyclerTemperatureFragment.newInstance();
FragmentManager manager = getFragmentManager();
dialog.show(manager,"DTAG");
}
}
但是当我启动它时,我收到了这个错误:
java.lang.IllegalStateException: Fragment RecyclerTemperatureFragment{b4d74cd} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:819)
at android.app.Fragment.getString(Fragment.java:841)
我怎么能解决这个问题?我在网上看了一个教程,但是在视频中这个代码可以工作但是在我的项目中崩溃了。
谢谢
答案 0 :(得分:3)
这一行可能会出错,因为获取资源需要上下文:
input type="submit"
尝试启动String[] items = {getString(R.string.kt),getString(R.string.mph),getString(R.string.kmh)};
答案 1 :(得分:1)
inflater.inflate(R.layout.fragment_recycler_temperature, container, false);
的最后一个参数(布尔值attachToRoot)应为true