我正在尝试在片段中向spinner添加项目。但我对上下文有疑问。因为在片段中没有上下文。这是我在做什么
public class DetailFrag extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View scrollView = inflater.inflate(R.layout.myscrollview , container, false);
LinearLayout linearLayout = (LinearLayout) scrollView.findViewById(R.id.mylayout1);
for (int i=0; i<questionList.size(); i++) {
View verticalLinearLayout = inflater.inflate(R.layout.mylistrow, null);
View horizontalLInearLaoyout = verticalLinearLayout.findViewById(R.id.questionRow);
TextView tv = (TextView) horizontalLInearLaoyout.findViewById(R.id.question);
Spinner spinner = (Spinner) horizontalLInearLaoyout.findViewById(R.id.spinner);
//Problem: how to define this in fragment createFromResource(this,...)
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.options_array, android.R.layout.simple_spinner_item);
EditText editText = (EditText) verticalLinearLayout.findViewById(R.id.txtMultiLine);
String question = questionList.get(i).question;
tv.setId(i);
tv.setText(i + question);
spinner.setId(i);
editText.setId(i);
linearLayout.addView(verticalLinearLayout);
}
return scrollView;
} //end of onCreateView()
} //end of class DetailFrag
答案 0 :(得分:17)
在片段中,上下文不能按照您在代码中的预期方式获得。而不是this
,请使用以下内容:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getBaseContext(),
R.array.options_array,
android.R.layout.simple_spinner_item);
答案 1 :(得分:0)
由于我们位于一个片段中,因此“ this”将无法正常工作: 应该使用getActivity()。getBaseContext()替换“ this”;
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(getActivity().getBaseContext(),
android.R.layout.simple_spinner_dropdown_item,
listItems);
请注意,在旧版本的Android上,还有getContext(),它也将返回片段的上下文,但是对于新版本,它可能不返回上下文。因此,使用getActivity()可以使您成为一个上下文活动。
答案 2 :(得分:-1)
做类似的事情:
private Context myContext = null;
public DetailFrag(Context ctx){
myContext = ctx;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
myContext, R.array.options_array, android.R.layout.simple_spinner_item);
//
}