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

Posted

技术标签:

【中文标题】如何解决片段中的 Viewpager 问题?【英文标题】:How to solve issue of Viewpager in a fragment? 【发布时间】:2021-05-08 11:01:53 【问题描述】:

这是我的应用程序的图像 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;



【问题讨论】:

【参考方案1】:

您同时附加ViewPagerDocumentFramgent,我假设mainContainerDocumentFragmentViewpager 也有DocumentFragment,这是导致问题的原因

如果您只想要一个片段,则可以删除onCreateMainActivity 中的第4 行

replace(R.id.maincontainer,new DocumentsFragment()).commit();//remove this line

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

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

【讨论】:

以上是关于如何解决片段中的 Viewpager 问题?的主要内容,如果未能解决你的问题,请参考以下文章

如何用 ViewPager 中的另一个片段替换 Android 片段?

如何更新 Tablayout 中的片段? (Viewpager2, FragmentStateAdapter)

viewpager 中的 3 个 android 片段,如何让它们全部存活?

当 ViewPager 中的片段出现和消失时如何执行一些代码

如何使用 TabLayout 在 ViewPager 中的 Google 地图片段中获取当前位置

带有 SlidingMenu 的片段中的 ViewPager