Fragment类中ArrayAdapter的上下文

A.M*_*oll 1 android listview android-fragments

我正在尝试为Android的Fragment实现listView的搜索栏。我让它在一项活动中正常工作,但现在我需要使其片段化。这是我的代码:

public class AboFragment extends Fragment {

String [] items;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
EditText editText;

public AboFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_abo, container, false);
    listView=(ListView)v.findViewById(R.id.listview);
    editText=(EditText)v.findViewById(R.id.textsearch);
    initList();
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(s.toString().equals("")){
                initList();
            }
            else{
                searchItem(s.toString());
            }
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    Button dealerActivity = (Button) v.findViewById(R.id.button_dealer);
    dealerActivity.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent startDealer = new Intent(getActivity(), DealerActivity.class);
            startActivity(startDealer);

        }
    });
    return v;
}

public void initList(){
    items = new String[]{"Canada", "China", "Japan", "USA"};
    listItems = new ArrayList<>(Arrays.asList(items));
    adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textitem, listItems);
    listView.setAdapter(adapter);
}

public void searchItem(String textToSearch){
    for(String item:items){
        if(!item.contains(textToSearch)){
            listItems.remove(item);
        }
    }
    adapter.notifyDataSetChanged();
}
Run Code Online (Sandbox Code Playgroud)

}

问题出在initList()方法中,我正在尝试为我的arraylist初始化适配器,但是我不确定如何修复它。它不接受“ this”。我也尝试了“ getContext”,但没有成功。错误消息是“无法解析构造函数”。如果我使用“ getActivity”作为上下文运行该应用程序,它不会崩溃,但搜索栏也不在那里。

Com*_*are 5

它不接受“ this”。

this是一个FragmentFragment不继承自Context

我也尝试了“ getContext”,但没有成功。

Fragment没有getContext()方法

使用getActivity()来获得托管的一个实例ActivityActivity继承自Context

但是搜索栏也不在那里。

那是一些单独的问题,例如您的布局。它与传递给ArrayAdapter构造函数的参数无关。