我正在将 imageView 添加到 LinearLayout,由于某种原因,clickListener 不适用于每个 imageView,所以我决定尝试将标签添加到 imageView,然后将其添加到 LinearLayout,然后当单击 LinearLayout 时我想要检查 View 标签以找出哪个 imageView 被按下。这是行不通的,特别是 View 标签始终为空。我希望能够区分点击了哪个图像。
以下内容采用每个图像的路径的数组列表,图像可以正常加载到屏幕上。
private void displayImages(ArrayList<String> al) {
final int THUMBSIZE = 640;//was originally 64
linearLayout1.removeAllViews();
for (int i = 0; i < al.size(); i++){
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory()+"/ImageSpace/"+al.get(i)),
THUMBSIZE, THUMBSIZE);
Drawable d = new BitmapDrawable(getResources(),ThumbImage);
imageView = new ImageView(MainActivity.this);
imageView.setBackground(d);
//linearLayout1.removeAllViews();
//imageView.setTag(i+"");
linearLayout1.addView(imageView);
linearLayout1.getChildAt(i).setTag(i+"");
}
}
这是 LinearLayout 点击监听器:
linearLayout1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "yeh", Toast.LENGTH_SHORT).show();
Log.v("TAG","views tag: "+v.getTag());
}
});
XML 布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/linearLayout1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="@drawable/ic_launcher"
android:onClick="test"/>
</LinearLayout>
</ScrollView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
另外,我正在初始化我使用的 imageView,
imageView = (ImageView) findViewById(R.id.imageView1);
这看起来可能是不正确的,因为它只会引用一个 imageView,这可能就是问题所在。
最佳答案
您想要为添加到 Linear Layout
中的每个 ImageView
设置 Id。
for (int i = 0; i < al.size(); i++){
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory()+"/ImageSpace/"+al.get(i)),
THUMBSIZE, THUMBSIZE);
Drawable d = new BitmapDrawable(getResources(),ThumbImage);
imageView = new ImageView(MainActivity.this);
imageView.setId(i);
imageView.setBackground(d);
//linearLayout1.removeAllViews();
//imageView.setTag(i+"");
linearLayout1.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v1) {
System.out.print("Imageview clikcked Path!::::" +al.get(v1.getId()));
}
}
});
}
当您点击任何ImageView
时,通过获取该 View 的ID来获取特定数据。试试这个。
关于java - 监听 LinearLayout 中 ImageView 的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186512/