2012-09-05 40 views
3

我試圖將項目添加到片段中的微調器。但是我對上下文有問題。因爲在片段中沒有上下文。這裏怎麼我做如何爲片段中的微調器設置ArrayAdapter

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 

回答

15

在片段,上下文是不可用在你的代碼預期的方式。取而代之的this,使用以下命令:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
    getActivity().getBaseContext(), 
    R.array.options_array, 
    android.R.layout.simple_spinner_item); 
+0

爲什麼'.getBaseContext()'? – hengxin

-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); 


// 
} 
+3

我用這個和它的工作的'getActivity()getApplicationContext()''而不是this'。 – Basit

+1

@Basit從不使用應用程序上下文來創建控件!更好地使用活動本身。通過應用程序上下文,您可以快速安全地泄漏上下文。 – rekire