2016-07-28 41 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