我使用Picasso
填充水平滾動視圖,問題是我無法正確實現onClickListener
,因爲那些列表的項目視圖沒有任何索引。實現水平滾動視圖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
列表的索引綁定到各自的SquaredImageView
項滾動型水平?在onClickListener裏面然後 public View insertPhoto(String path, final int position) {
:或者,也許你能提出更好的方法爲onClick
嘗試將onClickListener用於替代佈局 – scubasteve623 2015-04-01 13:46:05