错误 - 找不到适合ArrayAdapter的构造函数

时间:2016-07-28 10:14:51

标签: android constructor syntax-error

我在Android应用程序的一个选项卡中有这个代码: -

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)

我试图编辑它,但问题仍然存在

2 个答案:

答案 0 :(得分:1)

以下是您使用的ArrayAdapter的默认构造函数,您应该将Context作为第一个参数传递

  

ArrayAdapter(Context context,int resource,List objects)

所以改变

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

答案 1 :(得分:1)

尝试使用:

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

Fragment本身不是Context,您需要将上下文作为第一个参数传递: - )

作为旁注,您也可以使用getActivity()代替container.getContext(),但如果未附加Fragment,则可能会产生异常(如果您使用{{ 1}}在适配器中例如)