【发布时间】:2022-01-19 22:37:38
【问题描述】:
我正在尝试在 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();
}
}
问题在于 initList() 方法,我正在尝试为我的数组列表初始化适配器,但我不确定如何修复它。它不接受“这个”。我也尝试了“getContext”但没有成功。错误消息是“无法解析构造函数”。 如果我使用“getActivity”作为上下文运行应用程序,它不会崩溃,但搜索栏也不存在。
【问题讨论】:
-
不,不,不,适配器中的过滤是通过调用
adapter.getFilter().filter(constraint)完成的,SO 和网络上也有数百个示例 -
如果您想询问丢失的搜索栏,请询问该问题,而不是无关的错误
标签: android listview android-fragments