我正在尝试在Tab活动中实现可搜索的列表视图。因此,主页有3个选项卡,在第一个选项卡中,我需要一个带有搜索编辑文本框的列表视图。以下代码分别用作选项卡功能和带有搜索的列表视图。当我结合这些时,我得到了错误
adapter = new ArrayAdapter(this,R.layout.list_item,R.id.product_name,products); show add on demand静态包,仅删除R。
我不知道怎么回事。帮助将不胜感激。
package com.artificers.subin.inspection;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Subin on 13-10-2015.
*/
public class Tab1Fragment extends Fragment {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.tab1_view, container, false);
// Listview Data
String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
"iPhone 4S", "Samsung Galaxy Note 800",
"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
lv = (ListView) V.findViewById(R.id.list_view);
inputSearch = (EditText) V.findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Tab1Fragment.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
return V;
}
}
答案 0 :(得分:1)
问题是你使用“this”作为ArrayAdapter构造函数中的上下文参数,但Fragment不是Context的子类。
因此,在您的情况下,您必须使用下一个解决方案之一:
1º - 获取父活动:
// Adding items to listview
adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
2º - 获取背景信息:
// Adding items to listview
adapter = new ArrayAdapter<String>(getContext(), R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
希望有所帮助