为Horizo​​ntal ScrollView实现onClickListener

时间:2015-04-01 13:42:50

标签: android android-imageview horizontalscrollview onitemclicklistener picasso

我正在使用Picasso填充Horizo​​ntal ScrollView,问题是我无法正确实现onClickListener,因为列表的项目视图没有任何索引。

XML

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:id="@+id/myGallery">
    <LinearLayout
        android:id="@+id/channelsScrollView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        />
</HorizontalScrollView>

和代码

private void populateImages() {
    final List<String> urls = new ArrayList<>();

    //getting list of urls
    for (int i = 0; i < ActivityLoading.dataChannelsArrayList.get(0).getChannelArrayList().size(); i++) {
        urls.add(getString(R.string.get_channels_img_host) + ActivityLoading.dataChannelsArrayList.get(0).getChannelArrayList().get(i).getId());
    }

    //add views to horizontal scrollView by the amount of urls
    myGallery = (LinearLayout) findViewById(R.id.channelsScrollView);
    for (int i = 0; i < urls.size(); i++) {
        myGallery.addView(insertPhoto(urls.get(i), i));
    }
}

public View insertPhoto(String path, int position) {
    LinearLayout layout = new LinearLayout(getApplicationContext());
    layout.setGravity(Gravity.CENTER);
    final SquaredImageView squaredImageView = new SquaredImageView(getApplicationContext(), position);
    squaredImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    Picasso.with(this).load(path).placeholder(R.drawable.loading_small).into(squaredImageView);

    //I need to receive somehow the position of view pressed
    squaredImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             //this crashes here
            Toast.makeText(getApplicationContext(), squaredImageView.id, Toast.LENGTH_SHORT).show();
        }
    });
    layout.addView(squaredImageView);
    return layout;
}

如何将urls List的索引绑定到Horizo​​ntal ScrollView中的相应SquaredImageView项?或许你可以为onClick

建议更好的方法

1 个答案:

答案 0 :(得分:2)

选项1: 将position参数更改为final: public View insertPhoto(String path, final int position) {

然后在onClickListener中: 您可以访问位置参数。 Toast.makeText(getApplicationContext(), "POSITION: " + position, Toast.LENGTH_SHORT).show();

选项2: 设置squaredImageView的标记: squaredImageView.setTag(position);

然后在onClickListener中通过调用获取该标记: int location = (int)v.getTag();