废话之后再说,先上解决方案:
在你的getView方法的形参 int position前加上final,如图:
我们在做安卓软件开发时制作的ListView通常都需要设置若干监听事件,BaseAdapter便是理想的适配器。
今天记录一个在使用此适配器的时候遇到的一个小问题
出现题目问题的原因是,我在ListView上放了一个Button按钮,目的是想要对Button对应的商品进行数据的操作。如图:
界面不甚美观,UI大神轻喷。。
我报错的代码是这样的:
其实一开始我是想定义一个变量来获取position的值,算是偷梁换柱,然后我成功了!不报错了!
代码如下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(getContext(), R.layout.listview, null);
holder = new ViewHolder();
holder.img = convertView.findViewById(R.id.img);
holder.name = convertView.findViewById(R.id.gname);
holder.price = convertView.findViewById(R.id.price);
holder.date = convertView.findViewById(R.id.gdate);
holder.add= convertView.findViewById(R.id.add);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
p=position;//这里的p是我一开始定义的静态int(其实不是静态也可以,芜嗦胃的)
final String url = goods.getJSONObject(position).getString("address");
Glide.with(getContext()).load(url).into(holder.img);
holder.name.setText(goods.getJSONObject(position).getString("gname"));
holder.price.setText(goods.getJSONObject(position).getString("price"));
holder.date.setText(goods.getJSONObject(position).getString("date"));
holder.add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String gname =goods.getJSONObject(p).getString("gname");//这里就用p来代替position了
int price =goods.getJSONObject(p).getInt("price");
JSONObject good = new JSONObject();
good.put("gname",gname);
good.put("price",price);
HttpUtil.connection(HomeFragment.class, good, "AddGoodsServlet");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
然后,我运行程序,没有任何问题
但是当我点击“可比克”对应的Button后,数据库显示我加入购物车的是哑铃??为毛啊,淦
然后我陷入了沉思,想通了,这个position应该只对应的是最新出现的那个View,我的界面最后显示的是哑铃,所以不管是点击哪个Button,它都已经是哑铃的人了。
为了验证我的想法,我从下往上去翻这个列表后,position果然又指向了最上面新出现的那条View了。
意思是,这个position是一直变化的,所有已经出现的View,会随新出现的View一起变化position的值。
所以为了不让已经产生的position发生变化,把它定义成final,自然就解决这个问题了。
应该是我对这个适配器还不了解,所以这种小问题都不懂,今天在此记录一下这个,加深印象。
PS:文中的知识点仅是我个人想法,有错的还请各位指正。