首页 > 解决方案 > 如何访问 ViewPager 中布局整数中的 ImageView

问题描述

我为我的 ViewPager 制作了一个适配器,它从我的 MainActivity 中的一个整数中获取它的值。问题是我无法访问该布局内的图像视图。在这里你可以看到我的代码:

///*** Java 模型:

public class ZModel {
    final Integer alphabetViews;

    public ZModel(Integer alphabetViews) {
        this.alphabetViews = alphabetViews;
    }

    public Integer getAlphabetViews(){
        return alphabetViews;
    }
}

///*** Java 适配器:

final Context mContext;
    final ArrayList<ZModel> zModels;

    public ZAdapter(Context context, ArrayList<ZModel> zModels){
        this.mContext = context;
        this.zModels = zModels;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(zModels.get(position).getAlphabetViews(),container,false);
        container.addView(layout);

        return layout;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return zModels.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

///***主要活动2:

if ((Integer)imageView.getTag()==R.drawable.clock1) {
            alphabetViews = new Integer[]{R.layout.letter_blue, R.layout.letter_green, R.layout.letter_pink, R.layout.letter_red, R.layout.letter_yellow};

           ///***I wish to access the ImageViews which are in the above Layouts
        }

        if ((Integer)imageView.getTag()==R.drawable.clock2){
            alphabetViews = new Integer[]{R.layout.letter_yellow, R.layout.letter_red, R.layout.letter_pink, R.layout.letter_green, R.layout.letter_blue};
        }

///*** (letter_blue.xml) 详细信息


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright">

    <ImageView
        android:id="@+id/img_test1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/clock1" />

</androidx.constraintlayout.widget.ConstraintLayout>

如您所见,ViewPager 正在与 Activites 一起使用,它从 Integer 获取其值,我可以轻松地滑动它并且没有问题,只想访问几乎每个布局中的 imageview。

标签: javaandroid-studiointegerandroid-viewpager

解决方案


推荐阅读