2016-12-24 40 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文件中。

相關問題