這是TextView佈局。在動態生成的TextView中使用setOnClickListener()
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/trailer"
android:paddingTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"/>
這是主要的根部佈局。
<LinearLayout
android:id="@+id/review_layout"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
而這一段代碼添加textViews作爲上述線性佈局的childView,基於來自服務器的響應的總數。現在
@Override
public void addData(List<MovieVideoData> movieVideoDataList) {
trailerLinearLayout.removeAllViews();
List<TextView> textViews = new ArrayList<TextView>();
for (MovieVideoData movieVideoData:movieVideoDataList){
View view = getActivity().getLayoutInflater().inflate(R.layout.trailer_text_view,trailerLinearLayout,false);
((TextView)view.findViewById(R.id.trailer)).setText(movieVideoData.getName());
textViews.add(((TextView)view.findViewById(R.id.trailer)));
trailerLinearLayout.addView(view);
}
}
,爲其在線性佈局增加,對這些的點擊每個TextView的對象我想打開特定於該TextView的一個Youtube視頻鏈接。
我想知道,我應該如何使用每個textView的setOnClickListener()作爲ID都是相同的。
任何建議,將不勝感激。
我加了這段代碼,它工作正常。
private void watchYoutubeVideo(String key){
try{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + key));
startActivity(intent);
}catch (ActivityNotFoundException ex){
Intent intent=new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v="+key));
startActivity(intent);
}
}
textView.setText(movieVideoData.getName());
trailerLinearLayout.addView(view);
final String key = movieVideoData.getKey();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
watchYoutubeVideo(key);
}
});
在點擊每個文本視圖時,它會在youtube上打開各自的鏈接,這很好。
什麼我不知道的是,完成後循環movieVideoDataList,然後在文本視圖,它是如何記住具體關鍵,因爲它在循環內的點擊。
任何類型的澄清,將不勝感激。
簡單的方法是將不同的實例分配給每個TextView的 – Blackbelt
我想你可以新的偵聽設置爲每一個或者邏輯是相同的,也許你可以附加一個在你的活動中定義的聽衆 – kirotab
@Blackbelt謝謝你的回覆,我想過了。但是,如果我的arrayList的大小是10+,那怎麼辦?在這種情況下,如果必須爲所有對象設置偵聽器,並且我的代碼將不必要地增長。我想知道,如果有更好的解決方案。 – Ritesh