2016-07-28 42 views
1

我有這樣的代碼在Android應用程序的其中一個選項卡沒有合適的構造: -錯誤 - 發現ArrayAdapter

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.AutoCompleteTextView; 

public class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    public PlaceholderFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     String str[]={"Arun","Mathev","Vishnu","Vishal","Arjun", 
       "Arul","Balaji","Babu","Boopathy","Godwin","Nagaraj"}; 

     AutoCompleteTextView t1 = (AutoCompleteTextView) 
       rootView.findViewById(R.id.autoCompleteTextView1); 

     ArrayAdapter<String> adp=new ArrayAdapter<String>(this, 
       android.R.layout.simple_dropdown_item_1line,str); 

     t1.setThreshold(1); 
     t1.setAdapter(adp); 
     return rootView; 

和下面一行用紅色下劃線,因此引起的錯誤

(這一點,android.R.layout.simple_dropdown_item_1line,STR)

我試圖編輯它,但問題仍然存在

回答

1

這裏是ArrayAdapter你使用,你應該通過Context作爲第一個參數

ArrayAdapter(上下文的背景下,INT資源,List對象)的默認構造器

因此改變

ArrayAdapter<String> adp=new ArrayAdapter<String>(this, 
       android.R.layout.simple_dropdown_item_1line,str); 

ArrayAdapter<String> adp=new ArrayAdapter<String>(getActivity(), 
       android.R.layout.simple_dropdown_item_1line,str); 
+0

getActivity()不是最佳解決方案,因爲如果Fragment未附加,它將產生異常編輯:-( – Kelevandos

+0

@Kelevandos你是對的,但在某些情況下,我們仍然可以使用'getActivity()' –

+0

與我合作謝謝 – mh9

1

嘗試使用:

ArrayAdapter<String> adp=new ArrayAdapter<String>(
    container.getContext(),     
    android.R.layout.simple_dropdown_item_1line, 
    str); 

Fragment本身不是一個Context,你需要通過上下文:-)

作爲一個側面說明了第一個參數,你也可以使用getActivity()代替container.getContext(),但如果Fragment沒有連接(如果在適配器中使用Fragments),則這可能會產生一個例外

+0

它與我合作非常感謝 – mh9