【发布时间】:2019-01-18 21:47:04
【问题描述】:
我正在创建一个 Android 应用程序。它有一些带有搜索栏的弹出对话框。但问题是:当我使用它搜索某些产品时,该搜索的匹配项应该添加到弹出对话框内的列表视图中,这很好用。
但是当我选择项目时,弹出对话框中的搜索项目应该保存在我之前创建的对象 (OrderView object) 中,但是该对象内的存储项目总是错误 (仅当我搜索项目时才会发生这种情况)。问题出在这行代码,
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
因为我得到 postion 来识别所选项目。
但我不知道如何将此代码行替换为正确的方式。我真的很感谢你的帮助。谢谢你。
这是我的代码:
final List<Product> products_data = dbHelper.productListView();
if (products_data.size() > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select A Product");
//insert array to constructor
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.product_list_pop_up, null);
final ProdductPopupAdapter testAdapter = new ProdductPopupAdapter(getContext(), products_data);
final ListView listView = dialogLayout.findViewById(R.id.product_list_view);
TextView cancel_btn = dialogLayout.findViewById(R.id.cancel_btn);
final EditText search_view = dialogLayout.findViewById(R.id.list_item_search);
listView.setAdapter(testAdapter);
search_view.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) {
final ProdductPopupAdapter testAdapter = new ProdductPopupAdapter(getContext(),dbHelper.searchProductList(search_view.getText().toString()));
listView.setAdapter(testAdapter);
testAdapter.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable s) {
}
});
builder.setView(dialogLayout);
final AlertDialog alert = builder.create();
alert.show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
OrderView orderView = new OrderView();
orderView.setProduct_name(products_data.get(position).getProductName());
orderView.setProduct_qty(0);
orderView.setProduct_price(products_data.get(position).getPrice());
orderView.setNewItemtotal(Double.parseDouble(products_data.get(position).getPrice()));
orderView.setTotalPrice(products_data.get(position).getPrice());
orderView.setProduct_id(Integer.parseInt(products_data.get(position).getProductID()));
myItems.add(orderView);
calculatePrice(myItems);
binding.itemList.setAdapter(newOrderListAdaptor);
newOrderListAdaptor.notifyDataSetChanged();
alert.dismiss();
}
});
}
【问题讨论】:
-
您能否在 onItemClick 中为 products_data 和位置添加一些日志。然后我们就可以找到到底发生了什么。
-
我已经更新了我的帖子,第一张图片显示:所有产品列表都是这样的(搜索前)。 第二张图片显示: 当你搜索项目时,它会更新适配器并显示在弹出窗口中,如果我们认为你想将它添加到你的列表中,那么你应该选择它,现在会出现问题。 第三张图片显示: 已添加到列表中,但输入错误。这不是选定的值,这是第一个所有产品列表。
标签: android listview search adapter