Horizo​​ntalScrollView Views上的Android setOnClickListener()

时间:2014-09-21 10:04:08

标签: android

我正在使用以下代码填充horizo​​ntalscrollview:

 for(int I=0; I<jsonArraySize; I++)
        {               
            LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = vi.inflate(R.layout.best_seller_layout, null);

            TextView txtProductName = (TextView) v.findViewById(R.id.dashboard_bestSellerName);
            txtProductName.setText(bestSellersList.get(I).getProductName());                
            TextView txtPrice = (TextView) v.findViewById(R.id.dashboard_bestSellerPrice);
            txtPrice.setText(String.valueOf(bestSellersList.get(I).getProductUnitPrice()));             
            ImageView imgProductImage = (ImageView) v.findViewById(R.id.dashboard_bestSellerImage);
            imgProductImage.setImageBitmap(bestSellersImageList.get(I));                                

            insertPoint.add(findViewById(R.id.dashboard_mylinear));             
            ((ViewGroup) insertPoint.get(I)).addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));               

            final int K = I;                
            insertPoint.get(K).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(Dashboard.this,"The index is: " + K, Toast.LENGTH_SHORT).show();
                }
            });             
        }

这里,我使用setOnClickListener()来Toast每个视图的索引,但我总是得到最后一个索引而不是0,1,2 .....等。有以下几行可疑:

insertPoint.add(findViewById(R.id.dashboard_mylinear));

........也许所有布局看起来都是一样的因为这个,我不确定。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

根本不可腥。 “K”值为每个“for”迭代构建一次,而不是停止,而setOnClickListener函数正在构建并在每次按下单击时重新调用。因此,为了保持“K”值仍然相关,您必须从onClick函数中获取它。

答案 1 :(得分:0)

我认为问题在于将onClickListener设置为List Item。将侦听器设置为各个视图解决了问题:

            final int K = I;
            v.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeToast.makeText(Dashboard.this, "Pressed Index: "+ K, Toast.LENGTH_SHORT).show();
                }
            });
        }