2016-12-24 27 views
1

在我的XML文件,我有布局我的片段,其中包含HorizontalScrollView这样的:Horizo​​ntalScrollView OnClick方法引发错误

<HorizontalScrollView 
    android:id="@+id/srollview_seasons_gallery 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="left"> 
</HorizontalScrollView> 

在所谓season_list_item单独的XML文件我做了一个架构应该怎么项目单是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/season_image" 
     android:layout_marginLeft="7dp" 
     android:layout_marginRight="7dp" 
     android:onClick="seasonItemClicked"/> 

</RelativeLayout> 

我与我的Java代码动态添加的项目是这样的:

for (int i=0; i<seasonsSize; i++) { 
    View vi = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.season_list_item, null); 
    ImageView seasonImage = (ImageView) vi.findViewById(R.id.season_image); 
    //seasonImage.setId(i); 
    String imgUrl = response.body().getEmbedded().getSeasons().get(i).getImage().getMedium(); 
    Picasso.with(getContext()).load(imgUrl).into(seasonImage); 
    seasonsLinearLayout.addView(vi); 
} 
seasonsScrollView.addView(seasonsLinearLayout); 

当我执行我的onClick方法:

public void seasonItemClicked(View view) { 
    } 

我得到错误

java.lang.IllegalStateException:在为Android父母或祖先上下文找不到方法seasonItemClicked(查看):的onClick在视图类android.support.v7.widget.AppCompatImageView属性定义id为“season_image”

取消注释此行//seasonImage.setId(i);给我错误

android.content.res.Resources $ NotFoundException:无法找到资源ID#0x0`

照片添加到正确的布局,就像我希望他们。但我无法让他们点击。我还发现seasonImage.setId(i)对我来说很重要,因为我需要点击进行进一步操作的图片的编号。

你能帮我解决这个问题吗?

回答

1

问题是哪个叫你的方法seasonItemClicked()。尽可能多的视图你有这个属性,他们都会调用这个相同的方法,但是使用相同的ID android:id="@+id/season_image"
setId方法可能会非常烦人,因为您必须设置唯一 id。有some method to generate it,因此,对于每个图像,您必须生成一个唯一的ID,并且如果您动态设置它,请不要通过xml进行设置。

但是,假设您的图片数量可以变化,我宁愿以编程方式在for循环中添加点击侦听器。这样,它们将与点击的imageview相关。具体如下:

for (int i=0; i<seasonsSize; i++) { 
    ... 
    ImageView seasonImage = (ImageView) vi.findViewById(R.id.season_image); 
    seasonImage.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // perform your actions, be aware that 'view' here, is the image clicked 
     } 
    } 
    ... 
    seasonsLinearLayout.addView(vi); 
} 

而只是删除android:onclick属性:

<ImageView 
    ... 
    android:id="@+id/season_image" 
    android:layout_marginLeft="7dp" 
    android:layout_marginRight="7dp"/> 
+0

完美。谢谢 :) – dddeee

1

您正在分配冲突的ID,已分配给其他资源的ID。为编程创建的视图生成ID的最佳方法是使用View.generateViewId或将它们保留在res/values/ids.xml文件中。

相关问题