首页 > 解决方案 > 如何在 viewpager2 的每个页面中跟踪我的文本视图的可见性?

问题描述

所以这是我的代码。我正在尝试在我的应用程序中创建带有标题和描述的图像 PPT 幻灯片。

我有下面的代码,我被困在如何允许用户:

最后一部分是我坚持的,因为我无法弄清楚我的视图页面中的每个“线性布局”如何记住它的可见性并采取相应的行动。(即,一旦它不可见就会恢复可见,反之亦然)。

感谢您的意见。

请在下面找到代码:

我的 ViewPager XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/fragment_pager_main_parent"
    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="@drawable/default_background"
    tools:context=".PowerPointActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/fragment_pager_viewPager2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

我的意见 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/fragment_pager_item_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/fragment_pager_item_imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:scaleType="fitXY"/>

    <LinearLayout
        android:id="@+id/fragment_pager_item_main_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="textStart"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="@+id/fragment_pager_item_parent"
        app:layout_constraintStart_toStartOf="@+id/fragment_pager_item_parent">

        <!--            the linear layout below was not initially here but I was trying to have a layout for each child.-->
        <LinearLayout
        android:id="@+id/fragment_pager_item_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="textStart"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="@+id/fragment_pager_item_parent"
        app:layout_constraintStart_toStartOf="@+id/fragment_pager_item_parent">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/fragment_pager_item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginStart="10dp"
            android:layout_marginTop="5dp"
            android:gravity="top"
            android:textColor="#FFFFFF"
            android:textSize="12dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="@+id/fragment_pager_item_child"
            app:layout_constraintTop_toTopOf="@+id/fragment_pager_item_child"
            app:layout_constraintVertical_bias="0.0"
            tools:text="Topic" />

        <TextView
            android:id="@+id/fragment_pager_item_about"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="top"
            android:layout_marginStart="10dp"
            android:elegantTextHeight="true"
            android:text="@string/about_topic"
            android:textColor="#ffffff"
            android:textSize="12sp"
            app:layout_constraintHorizontal_bias="10"
            app:layout_constraintStart_toStartOf="@+id/fragment_pager_item_title"
            app:layout_constraintTop_toBottomOf="@id/fragment_pager_item_title"
            app:layout_dodgeInsetEdges="left" />
            </LinearLayout>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

我的适配器类:

public class PowerpointAdapter extends RecyclerView.Adapter{

    private List<Image> mPowerPointList;

    static class PagesViewHolder extends RecyclerView.ViewHolder {
        private ImageView mViewImageView;
        private TextView mTitleView;
        private TextView mDescriptionView;
        private LinearLayout mLinearLayout;

        public PagesViewHolder(@NonNull View itemView) {
            super(itemView);
            Timber.i("PagesViewHolder");
            mViewImageView = itemView.findViewById(R.id.fragment_pager_item_imageView);
            mTitleView = itemView.findViewById((R.id.fragment_pager_item_title));
            mDescriptionView = itemView.findViewById(R.id.fragment_pager_item_about);
            mLinearLayout = itemView.findViewById(R.id.fragment_pager_item_child);
        }
    }

    public PowerpointAdapter(List<Image> mPowerPointList) { this.mPowerPointList = mPowerPointList;}

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Timber.i("onCreateViewHolder");
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_pager_item, parent, false);
        return new PagesViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Timber.i("onBindViewHolder");
        PagesViewHolder mViewHolder = (PagesViewHolder) holder;
        Image powerpoint = mPowerPointList.get(position);
        mViewHolder.mViewImageView.setImageResource(powerpoint.getTrialImage());
        mViewHolder.mTitleView.setText(powerpoint.getTitle());
        mViewHolder.mDescriptionView.setText(powerpoint.getDescription());
        mViewHolder.mLinearLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public int getItemCount()  {
        Timber.i("getItemCount");
        return mPowerPointList.size();}

我的活动课:

// for a one image display, the image can be treated similarly to a powerpoint.

public class PowerPointActivity extends Activity {
    private ViewPager2 viewPager2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Timber.i("onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager_main);
        ConstraintLayout mLayout = findViewById(R.id.fragment_pager_main_parent);
        mLayout.setBackgroundResource(R.color.Transparent_black);
        viewPager2 = findViewById(R.id.fragment_pager_viewPager2);
        setUpPagerAdapter();
    }
    /**
     * this method will set up the adapter
     */
    private void setUpPagerAdapter() {
        Timber.i("SetUpPagerAdapter");
        PowerpointAdapter pagerAdapter = new PowerpointAdapter(fetchDummyData());
        viewPager2.setAdapter(pagerAdapter);
        viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
    }
    /**
     * @return this method will return dummy data in form of list
     */
    private List<Image> fetchDummyData() {
        Timber.i("fetchDummyData in Power Point Activity");
        List<Image> powerpointList = new ArrayList<>();
        String[] dummyArrDescriptions = getResources().getStringArray(R.array.array_str_descriptions_for_powerPoints);
        String[] dummyArrTitles = getResources().getStringArray(R.array.array_str_titles_for_powerPoints);
        for (int index = 0; index < dummyArrTitles.length; ++index) {
            Image image = new Image(dummyArrTitles[index], dummyArrDescriptions[index], R.drawable.ppt_image);
            powerpointList.add(image);
        }
        return powerpointList;
    }
    /**
     * this method handles slideshow navigation
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Timber.i("OnKeyDown");
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT: {
                viewPager2.setCurrentItem(viewPager2.getCurrentItem() - 1);
                Toast.makeText(PowerPointActivity.this, "Left pressed!", Toast.LENGTH_SHORT).show();
                break;
            }
            case KeyEvent.KEYCODE_DPAD_RIGHT: {
                viewPager2.setCurrentItem(viewPager2.getCurrentItem() + 1);
                Toast.makeText(PowerPointActivity.this, "Right pressed!", Toast.LENGTH_SHORT).show();
                break;
            }
            case KeyEvent.KEYCODE_BACK: {
                Toast.makeText(PowerPointActivity.this, "Back pressed!", Toast.LENGTH_SHORT).show();
                super.onBackPressed();
                break;
            }

            // todo: Fix the visibility of each page description

            case KeyEvent.KEYCODE_ENTER: {
                if (findViewById(R.id.fragment_pager_item_child).isShown()) {
                    Timber.i("It is shown. Setting it to not shown! "+ viewPager2.getCurrentItem() + " now.");

               // here this specific child's text should be set to invisible and remembered.     findViewById(R.id.fragment_pager_item_child).setVisibility(View.INVISIBLE);
                    LinearLayout mLayout = findViewById(R.id.fragment_pager_item_child);
                    Animation outFade = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
                    mLayout.startAnimation(outFade);
                    mLayout.startAnimation(outFade);
                    break;
                } else {
                    Timber.i("It is now not shown. Setting it to shown! " + viewPager2.getCurrentItem() + " now.");
                    LinearLayout mLayout = findViewById(R.id.fragment_pager_item_child);
                    Animation aniFade = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
                    mLayout.startAnimation(aniFade);
                    mLayout.startAnimation(aniFade);
                    findViewById(R.id.fragment_pager_item_child).setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        return false;
    }
}

谢谢!

标签: androidandroid-recyclerviewandroid-viewpagervisibility

解决方案


Android 文档中我们可以发现,它Adapter具有以下职责:

  • 充当 AdapterView 和该视图的基础数据之间的桥梁。
  • 提供对数据项的访问
  • 负责为数据集中的每一项制作一个View。

所以基本上,记住孩子的可见性并对其采取行动并不是视图的工作。是PowerpointAdapter责任。

您需要Image对象中的状态字段,并在视图可见性更改时对其进行更改。另外,不要忘记根据此状态变量设置视图可见性。

例如:

 @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Timber.i("onBindViewHolder");
        PagesViewHolder mViewHolder = (PagesViewHolder) holder;
        Image powerpoint = mPowerPointList.get(position);
        mViewHolder.mViewImageView.setImageResource(powerpoint.getTrialImage());
        mViewHolder.mTitleView.setText(powerpoint.getTitle());
        mViewHolder.mDescriptionView.setText(powerpoint.getDescription());
        if(powerpoint.isLayoutVisibile){ 
          mViewHolder.mLinearLayout.setVisibility(View.VISIBLE);
        }else{
          mViewHolder.mLinearLayout.setVisibility(View.GONE);
        }
    }

在您的内部,您ClickListener应该更改此字段并通知PowerpointAdapter这些更改。


推荐阅读