如何解决片段中的 Viewpager 问题?

How to solve issue of Viewpager in a fragment?

这是我的应用程序的图片 enter image description here

我卡在正确的选项卡位置加载片段。 每当我 运行 我的应用程序时,我的第一个选项卡中的片段显示在 viewpager 的所有选项卡中,并且第一个选项卡文件再次显示在片段上。

这是我的MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportFragmentManager().beginTransaction().
    replace(R.id.maincontainer,new DocumentsFragment()).commit();

    mviewPagerAdapter=new ViewPagerAdapter(getSupportFragmentManager());
    mViewPager=findViewById(R.id.viewpager);
    TabLayout tabLayout=findViewById(R.id.tabMode);
    tabLayout.setupWithViewPager(mViewPager);

   

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
       
        setviewPager(mViewPager);
    } else {
        requestStoragePermission();

    }

}

int Request_Code = 12;
private void setviewPager(ViewPager viewPagerAdapter)
{
    ViewPagerAdapter viewAdapter=new ViewPagerAdapter(getSupportFragmentManager());

viewAdapter.addFragment(new DocumentsFragment(),"Documents");
viewAdapter.addFragment(new FavouritesFragment(),"History");
viewAdapter.addFragment(new HistoryFragment(),"Favourites");
viewPagerAdapter.setAdapter(viewAdapter);
viewAdapter.notifyDataSetChanged();
}

private String[] permissionres = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission() {

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Request_Code);

}

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == Request_Code) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
           
            setviewPager(mViewPager);
          
        }
    } else {

    }
}

这是我的 recyclerAdapter 代码

  package com.example.flashxpdfreader;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.util.FitPolicy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

 public class RecylerAdapter extends RecyclerView.Adapter<RecylerAdapter.ViewHolder>{
List<File> pdf;
  private Interface inter;


public RecylerAdapter(List<File> pdf)
{
    this.pdf=pdf;
}

@Override
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    View view =layoutInflater.inflate(R.layout.single_row,parent,false);
    ViewHolder viewHolder= new ViewHolder(view);
    return  viewHolder;

}

@Override
public void onBindViewHolder( ViewHolder holder, int position) {
    holder.pdfsize.setText(String.valueOf(position));
    holder.pdfname.setText(pdf.get(position).getName());



          
   
}

@Override
public int getItemCount() {
    return pdf.size();
}

class  ViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView pdfname,pdfsize;
    public ViewHolder( View itemView) {
        super(itemView);

        imageView = itemView.findViewById(R.id.imageView);
        pdfname = itemView.findViewById(R.id.pdfname);
        pdfsize=itemView.findViewById(R.id.pdfsize);
 itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    inter.onItemClick(getAdapterPosition());
}
});
    }



}
}

这是我的 ViewpagerAdapter 代码

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragmentlist=new ArrayList<>();
private final List<String> fragmentTitleList=new ArrayList<String>();
public ViewPagerAdapter(@NonNull FragmentManager fm) {
    super(fm);
}

@NonNull
@Override
public Fragment getItem(int position) {
    return fragmentlist.get(position);

}



@Override
public int getCount() {
    return fragmentlist.size();
}
public void addFragment(Fragment fragment,String title)
{
    fragmentlist.add(fragment);
    fragmentTitleList.add(title);
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return fragmentTitleList.get(position);
}
}

这是我的 DocumentsFragment 代码:

public class DocumentsFragment extends Fragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
RecyclerView recyclerView;
RecylerAdapter recyclerAdapter;
List<File> pdf=new ArrayList<>();
File file;


public DocumentsFragment() {

}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment DocumentsFragment.
 */
// TODO: Rename and change types and number of parameters
public static DocumentsFragment newInstance(String param1, String param2) {
    DocumentsFragment fragment = new DocumentsFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   View view= inflater.inflate(R.layout.fragment_documents, container, false);
   file = new File(Environment.getExternalStorageDirectory().toString());
   getlistfiles(file);
    recyclerView=view.findViewById(R.id.recview);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(new RecylerAdapter(pdf));
    return view;
}
private List<File> getlistfiles(File direc)
{
    File[] doc=direc.listFiles();
    for(File docs:doc)
    {
        if(docs.isDirectory())
        {
            getlistfiles(docs);
        }
        else
        {

            if (docs.getName().endsWith(".pdf")) {

                pdf.add(docs);
            }
        }

    }
    return pdf;
}

}

您同时附加了 ViewPagerDocumentFramgent,我假设 mainContainerDocumentFragment 并且 Viewpager 也有 DocumentFragment,这是导致问题的原因

如果您只想要一个片段,则可以删除 onCreate of MainActivity

中的第 4 行
replace(R.id.maincontainer,new DocumentsFragment()).commit();//remove this line

如果你想要两者,那么在 ViewPager 中你需要添加 backgroundColorclickablefocusable 这样底层的 fragment 将不可见可触摸

android:background="@color/<yourbackgroundcolor>"
android:clickable="true"
android:focusable="true"