[英]Error populating spinner in a fragment
I have a Activity with two fragments. 我有一个活动有两个片段。 One of them hava a spinner.
其中一个有旋转器。 When I populate it the app crashes.
当我填充它时,应用程序崩溃。 I don't know why.
我不知道为什么。 In android developers it's confused how do it in fragments, it seems is diferent like normal activity.
在Android开发人员中,它如何在片段中混淆,它似乎与正常活动不同。
Thanks! 谢谢!
public class InstrumentsFrag extends Fragment {
TextView tv1;
Spinner sp;
String[] os = {"Cupcake v1.5", "Donut v1.6", "Éclair v2.0/2.1", "Froyo v2.2",
"Gingerbread v2.2", "Honeycomb v3.0/3.1"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.instruments, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = (Spinner) getActivity().findViewById(
R.id.spinner1);
ArrayAdapter <CharSequence>adapter = ArrayAdapter.createFromResource( getActivity(), R.array.sections , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
I had the same problem where my app crashed when populating a spinner. 我有同样的问题,我的应用程序在填充微调器时崩溃了。 In my case, the spinner I was populating was defined in the fragment's XML file, so the trick was getting findViewById() to find it.
在我的例子中,我填充的微调器是在片段的XML文件中定义的,所以诀窍是让findViewById()找到它。 I see in your case you tried to use getActivity():
我看到你试图使用getActivity():
sp = (Spinner) getActivity().findViewById(R.id.spinner1);
I also tried using both getActivity() and getView(), and both caused crashes (null spinner, and NULL Pointer exception respectively). 我也尝试使用getActivity()和getView(),并且两者都导致崩溃(分别为null spinner和NULL Pointer异常)。
I finally got this to work by replacing getActivity() with the fragment's view. 我终于通过用片段的视图替换getActivity()来实现这一点。 I did this by populating the spinner when onCreateView() is called.
我通过在调用onCreateView()时填充微调器来完成此操作。 Here are some snippets from my final code:
以下是我最终代码中的一些片段:
private Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.myFragmentXmlFile, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
...
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.mySpinner );
...
spinner.setAdapter( adapter );
...
}
So I passed the fragment view into my function and referenced that view to configure the spinner. 所以我将片段视图传递给我的函数并引用该视图来配置微调器。 That worked perfectly.
这非常有效。 (And quick disclaimer - I'm new to Android myself, so perhaps some of the above terminology can be corrected or clarified if needed by more experienced people.)
(并且快速免责声明 - 我自己也是Android的新手,所以如果更有经验的人需要,也许可以纠正或澄清上述一些术语。)
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.