Android中切换标签片段之间的延迟

Posted

技术标签:

【中文标题】Android中切换标签片段之间的延迟【英文标题】:Lag between switching tab fragment in Android 【发布时间】:2018-02-05 10:38:28 【问题描述】:

我遇到的问题是,每当我在不同的选项卡之间切换时,该过程都会滞后一两秒。我怎样才能消除这种滞后?片段的 oncreate 函数中没有这样的东西。我在这里发布代码。

这是调用片段 Dashboardnew 的活动的代码:

private void setupDrawerContent(final NavigationView navigationView) 
    //revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
    expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() 
        @Override
        public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) 
            if(i==0) 
                //Toast.makeText(getApplicationContext(),"View Tasks",Toast.LENGTH_LONG).show();
                fab.setVisibility(View.VISIBLE);
                if (filterApplied) 
                    persistentbottomSheet.setVisibility(View.VISIBLE);
                    persistentbottomSheet.bringToFront();
                    fab.bringToFront();
                
                fragment = new DashboardNew();
                if (fragment != null) 
                    manager.beginTransaction().replace(R.id.dashboard_frame, fragment).commit();
                    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                    drawer.closeDrawer(GravityCompat.START);
                
              /* new Handler().postDelayed(new Runnable() 
                    @Override
                    public void run() 
                        if (fragment != null) 
                            manager.beginTransaction()
                                    .replace(R.id.dashboard_frame, fragment)
                                    .commit();

                        
                    
                , 300);*/
                //drawer.closeDrawer(GravityCompat.START);
            

            if(i==1) 

            

            if(i==2) 
                prefs.edit().remove("firstTime").apply();
                Intent intent = new Intent(getApplication(), Login.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                finish();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            

            return false;
        
    );

    expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() 
        @Override
        public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) 
            if (groupPosition == 1 && childPosition == 0) 
                fabvisibility = false;
                //so this code only executes if the 2nd child in the 2nd group is clicked
                fragment=new AddUser();
                if (fragment != null) 
                    manager.beginTransaction()
                            .replace(R.id.dashboard_frame, fragment,"AddUser")
                            //.add(fragment,"AddUser")
                           // .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                            .commit();
                
                drawer.closeDrawer(GravityCompat.START);
            

            if (groupPosition == 1 && childPosition == 1) 
                //so this code only executes if the 2nd child in the 2nd group is clicked
                fabvisibility = false;
                fragment=new ViewUsers();
                if (fragment != null) 
                    manager.beginTransaction()
                            .replace(R.id.dashboard_frame, fragment)
                            .commit();
                    drawer.closeDrawer(GravityCompat.START);
                
            

            return false;
        
    );


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in androidManifest.xml.
    switch (item.getItemId()) 
        case android.R.id.home:
            drawer.openDrawer(GravityCompat.START);
            return true;
    

    return super.onOptionsItemSelected(item);


Dashboardnew 片段的代码是:

    initialize(rootview);
    clicklisteners();
    createViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);
    createTabIcons();

    return rootview;


 private  void clicklisteners()
 
     usualTasks.setOnClickListener(this);
 
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) 
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("The Checklist");

 @Override
 public  void onClick(View v) 
     switch (v.getId()) 
         case R.id.toggleButton: 

             if(usualTasks.isChecked()) 
                 Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
                 showRoleDialog();
                 FragmentTransaction trans = getFragmentManager().beginTransaction();
                 trans.replace(R.id.base_pending, new UsualTasks());

                 WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
                 //WelcomeActivity.fab.setVisibility(View.INVISIBLE);

                 trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                 trans.commit();
             
             else 
                 Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
                 FragmentTransaction trans = getFragmentManager().beginTransaction();
                 trans.replace(R.id.usual_pending, new PendingTasks());
                 trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                 if (WelcomeActivity.filterApplied == true) 
                     WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
                     WelcomeActivity.persistentbottomSheet.bringToFront();
                     WelcomeActivity.fab.setVisibility(View.VISIBLE);

                 
                 if(UsualTasks.shown) 
                     UsualTasks.mSnackBar.dismiss();
                 

                 trans.commit();
             
         
     
 

public void populateList(HashMap<Integer, String> myMap, List myList)
    Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
    Iterator<Map.Entry<Integer,  String>> iteratorMap = setMap.iterator();
    int item=0;
    while(iteratorMap.hasNext()) 
        Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
        myList.add(entry.getValue());
        item++;
    


private  void showRoleDialog() 
     final Dialog dialog = new Dialog(getContext());
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
     dialog.setContentView(R.layout.usualtask_dialog);
     rolelist = new ArrayList<Map<Integer,String>>();
     roles= new HashMap<Integer, String>();

     roles.put(1, "Senior Manager");
     roles.put(2, "Admin");
     roles.put(3, "HR");
     populateList(roles,rolelist);

     ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_single_choice, rolelist)
     
         @Override
         public View getView(int position, View convertView, ViewGroup parent)
             // Get the current item from ListView
             View view = super.getView(position,convertView,parent);
             TextView tv = (TextView) view.findViewById(android.R.id.text1);
             tv.setTextColor(Color.parseColor("#353b41"));
             return view;

         
     ;
     dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

     selectRole= (ListView)dialog.findViewById(R.id.selectrole);
     submitRole= (Button)dialog.findViewById(R.id.btsubmitrole);
     selectRole.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
     selectRole.setAdapter(arrayAdapter);

     selectRole.setOnItemClickListener(new AdapterView.OnItemClickListener() 
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
     );

    submitRole.setOnClickListener(new View.OnClickListener()

         @Override
         public void onClick(View view) 
             dialog.dismiss();
         
     );

     dialog.show();
 

private void createTabIcons() 
    RelativeLayout tabOne = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.pending_tab, null);
    TextView textTab=(TextView)tabOne.findViewById(R.id.tab);
    ImageView imageTab=(ImageView) tabOne.findViewById(R.id.notifyimage);

    //TextDrawable drawable = TextDrawable.builder().buildRound("999",Color.RED); // radius in px
    TextDrawable drawable = TextDrawable.builder()
            .buildRoundRect("999",Color.RED,18); // radius in px
    imageTab.setImageDrawable(drawable);
    textTab.setText("Pending");
    tabLayout.getTabAt(1).setCustomView(tabOne);

    RelativeLayout tabTwo = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.completed_tab, null);
    TextView textTab1=(TextView)tabTwo.findViewById(R.id.pending_tab);
    textTab1.setText("Completed");
    tabLayout.getTabAt(0).setCustomView(tabTwo);


private void initialize(View rootview) 
    toolbar = (Toolbar)rootview.findViewById(R.id.toolbar);
    viewPager = (ViewPager)rootview.findViewById(R.id.viewpager);
    tabLayout = (TabLayout)rootview.findViewById(R.id.tabs);
    usualTasks=(ToggleButton)rootview.findViewById(R.id.toggleButton);


private void createViewPager(ViewPager viewPager) 
        adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
        adapter.addFrag(new CompletedTasks(), "Completed");
        adapter.addFrag(new PendingTasks(), "Pending");
        viewPager.setAdapter(adapter);


class ViewPagerAdapter extends FragmentPagerAdapter 
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    public ViewPagerAdapter(FragmentManager manager) 
        super(manager);
    

    @Override
    public Fragment getItem(int position) 
        if (position == 0)
            return new CompletedTasks();
        else
            return new PendingTasks();
    

    @Override
    public int getCount() 
        return mFragmentList.size();
    

    public void addFrag(Fragment fragment, String title) 
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    

    @Override
    public CharSequence getPageTitle(int position) 
        return mFragmentTitleList.get(position);
    


这里是已完成任务的代码:

    completedTaskList = (ListView) rootview.findViewById(R.id.completedlist);
    BaseMenuActivity.filterState=false;

    if(UsualTasks.shown) 
        UsualTasks.mSnackBar.dismiss();
    

    generateListdata();

    return rootview;


private void generateListdata() 
    completedTasks.add(new completedTasks("Call the Owner","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
    completedTasks.add(new completedTasks("Check the safety of patients","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.safety_dashboard));
    completedTasks.add(new completedTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.admin_dashboard));
    completedTasks.add(new completedTasks("Get the specific work done","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
    completedTasks.add(new completedTasks("Need to hire more resources","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.hr_dashboard));
    completedTasks.add(new completedTasks("How are patients behaving?","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.patient_experience_dashboard));
    completedTasks.add(new completedTasks("Need to adjust the audit report","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.finance_dashboard));

    //getListView().setDividerHeight(10);
    ArrayAdapter<com.example.attech.checklist_attech.Model.completedTasks> adapter = new CompletedTaskAdapter(getContext(), 0,completedTasks);
    completedTaskList.setAdapter(adapter);

    completedTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) 
            if (position == 0) 

            if (position == 1) 

            if (position == 2) 
                //Intent myIntent = new Intent(view.getContext(), ViewUser.class);
                //startActivityForResult(myIntent, 0);
            
        
    );




这是挂起任务的代码:

initialize(rootview);
        generateListdataAssigned();
        generateListdata();
        generateselectall();
        clickListeners();

        return rootview;
    

    private void clickListeners() 
        assignTask.setOnClickListener(this);
        assignTaskbottom.setOnClickListener(this);
    

    private void populateList(HashMap<Integer, String> myMap, List myList)
        Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
        Iterator<Map.Entry<Integer,  String>> iteratorMap = setMap.iterator();
        int item=0;
        while(iteratorMap.hasNext()) 
            Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
            myList.add(entry.getValue());
            item++;
        
    


    @Override
    public void onClick(View v) 
        switch (v.getId()) 
            case R.id.assignTaskPending: 
                selected = !selected;

                if (selected) 
                    Toast.makeText(getActivity(), "Assigned", Toast.LENGTH_LONG).show();
                    assignTask.setBackgroundResource(R.color.dark_grey);
                    Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
                    pendingTaskListAssigned.setVisibility(View.VISIBLE);
                    WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
                    selectAllListView.setVisibility(View.VISIBLE);
                    assignTaskbottom.setVisibility(View.VISIBLE);
                    pendingTaskList.setVisibility(View.INVISIBLE);

                
                else 
                    Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
                    Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
                    pendingTaskListAssigned.setVisibility(View.INVISIBLE);
                    assignTaskbottom.setVisibility(View.INVISIBLE);
                    selectAllListView.setVisibility(View.INVISIBLE);
                    assignTask.setBackgroundResource(R.drawable.box_grey);
                    pendingTaskList.setVisibility(View.VISIBLE);
                    if (WelcomeActivity.filterApplied) 
                        WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
                        WelcomeActivity.persistentbottomSheet.bringToFront();
                        WelcomeActivity.fab.setVisibility(View.VISIBLE);

                    
                

                break;
            

            case R.id.btassignTask: 
                showAssignTaskDialog();
                break;
            
        
    

    private  void initialize(View rootview) 
        pendingTaskList = (ListView) rootview.findViewById(R.id.pendinglist);
        pendingTaskListAssigned = (ListView) rootview.findViewById(R.id.pendinglistassigned);
        assignTask = (Button) rootview.findViewById(R.id.assignTaskPending);
        assignTaskbottom = (Button) rootview.findViewById(R.id.btassignTask);
        selectAllListView= (ListView)rootview.findViewById(R.id.selectalllist);
    

    private void generateListdataAssigned() 
        pendingTasksAssigned.add(new pendingTasks("System Tasks","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
        pendingTasksAssigned.add(new pendingTasks("Call answer speed","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
        pendingTasksAssigned.add(new pendingTasks("Appointment reasons","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
        pendingTasksAssigned.add(new pendingTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.hr_dashboard));

        ArrayAdapter<pendingTasks> adapter = new PendingAssignedAdapter(getContext(), 0, pendingTasksAssigned);
        pendingTaskListAssigned.setAdapter(adapter);
        pendingTaskListAssigned.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                CheckBox checkBox=(CheckBox)view.findViewById(R.id.checkboxassigned);
                checkBox.performClick();

                if(checkBox.isChecked())
                    countChecks = countChecks + 1;
                
                else
                    countChecks = countChecks - 1;
                

                if(check == true)
                    selectAllListView.setItemChecked(0, false);
                    check = !check;
                

                if(countChecks == pendingTaskListAssigned.getCount())
                    selectAllListView.setItemChecked(0, true);
                    check = ! check;
                
            
        );
    

    //populating the arraylist, creating an adapter and setting it to a list view
    private void generateListdata() 
        pendingTasks.add(new pendingTasks("System Tasks", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
        pendingTasks.add(new pendingTasks("Call answer speed", "Wembley GP", "Daily",  R.drawable.pending_clock_icon, R.drawable.access_dashboard));
        pendingTasks.add(new pendingTasks("Appointment reasons", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.access_dashboard));

        ArrayAdapter<pendingTasks> adapter = new PendingTaskAdapter(getContext(), 0, pendingTasks);
        pendingTaskList.setAdapter(adapter);
        pendingTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                showInputDialog();

                if (position == 0) 

                if (position == 1) 
                    //Intent myIntent = new Intent(view.getContext(), AddUser.class);
                    //startActivityForResult(myIntent, 0);
                

                if (position == 2) 
                    //Intent myIntent = new Intent(view.getContext(), ViewUser.class);
                    //startActivityForResult(myIntent, 0);
                
            
        );
    

    private  void generateselectall() 
        selectallList= new ArrayList<Map<Integer,String>>();
        selectall= new HashMap<Integer, String>();

        selectall.put(1, "Select All");
        populateList(selectall,selectallList);
        ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_list_item_single_choice, selectallList)
        
            @Override
            public View getView(int position, View convertView, ViewGroup parent)
                // Get the current item from ListView
                View view = super.getView(position,convertView,parent);
                TextView tv = (TextView) view.findViewById(android.R.id.text1);
                tv.setTextColor(Color.BLACK);
                tv.setTextSize(13);
                ViewGroup.LayoutParams params = view.getLayoutParams();
                // Set the height of the Item View
                params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
                view.setLayoutParams(params);
                view.setPadding(37,0,10,10);
                return view;
            
        ;



        selectAllListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        selectAllListView.setAdapter(arrayAdapter);
        selectAllListView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                //Toast.makeText(getContext(), "Hello", Toast.LENGTH_SHORT).show();
                int firstListItem = pendingTaskListAssigned.getFirstVisiblePosition();
                int lastVisibleItem = pendingTaskListAssigned.getFirstVisiblePosition() + pendingTaskListAssigned.getChildCount() - 1;
                check = ! check;

                for(int i=0; i < pendingTaskListAssigned.getCount(); i++)
                    if(i>lastVisibleItem || i<firstListItem)
                        View item = (View) pendingTaskListAssigned.getAdapter().getView(i, null, pendingTaskListAssigned);
                        CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
                        checkbox.setChecked(check);
                    
                    else
                        ViewGroup item = (ViewGroup)pendingTaskListAssigned.getChildAt(i - firstListItem);
                        CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
                        checkbox.setChecked(check);
                    
                

                if(check == true)
                    countChecks = pendingTaskListAssigned.getCount();
                
                else
                    countChecks = 0;
                
            
        );
    

    protected void showInputDialog() 
        final  Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.task_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        tbutton = (ToggleButton)dialog.findViewById(R.id.toggleButton);
        toollamp= (ImageButton)dialog.findViewById(R.id.lamptool);
        tooli= (ImageButton)dialog.findViewById(R.id.itool);
        tooldetails= (TextView) dialog.findViewById(R.id.tooldetail);
        submit=(Button)dialog.findViewById(R.id.btsubmit);

        toollamp.setOnClickListener(new View.OnClickListener()

            @Override
            public void onClick(View view) 
                tooldetails.setText("Target for staff 2 rings and answer.Check daily for 2x 5 mins");
            
        );

        submit.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                //Toast.makeText(getActivity(), "Dismiss", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            
        );

        tooli.setOnClickListener(new View.OnClickListener()

            @Override
            public void onClick(View view) 
                tooldetails.setText("Check daily for 2x 5 mins");
            
        );

        tbutton.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                if(tbutton.isChecked()) 
                    Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
                
                else 
                    Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
                
            
        );

        dialog.show();
    

    protected void showAssignTaskDialog() 
        final Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.assign_task_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Close= (ImageButton)dialog.findViewById(R.id.close);
        myself=(Button)dialog.findViewById(R.id.btmyself);
        others=(Button)dialog.findViewById(R.id.btothers);

        Close.setOnClickListener(new View.OnClickListener()

            @Override
            public void onClick(View view) 
                dialog.dismiss();
            
        );

        myself.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                Toast.makeText(getActivity(), "Myself", Toast.LENGTH_LONG).show();
            
        );

        others.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                Toast.makeText(getActivity(), "Others", Toast.LENGTH_LONG).show();
                Intent intent= new Intent(getContext(), AssignTasks.class);
                startActivity(intent);
            
        );

        dialog.show();
    

【问题讨论】:

先显示你的代码 =) fragment 有 onResume.. 你有多少个标签?你加载什么数据?您的 xml 中有多少层次结构? 代码现在在这里 :D 我也是 *** 的新手...所以我也用 *** 编写了如何将代码添加到问题中 xD @Pousti 显示 CompletedTasks 片段和 PendingTasks 片段 @DEADMC 我刚刚更新了它。很抱歉给您带来不便 【参考方案1】:

对于那些有这个问题的人,请使用cardviews和recyclerviews。列表视图的数据太多。使用 cardviews 和 recyclerviews 代替,滞后消失了。

【讨论】:

【参考方案2】:

首先我不明白你为什么要创建两次片段

你实际上在这里创建片段

private void createViewPager(ViewPager viewPager) 
        adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
        adapter.addFrag(new CompletedTasks(), "Completed");
        adapter.addFrag(new PendingTasks(), "Pending");
        viewPager.setAdapter(adapter);

然后你在这里创建它们。再次

@Override
public Fragment getItem(int position) 
    if (position == 0)
        return new CompletedTasks();
    else
        return new PendingTasks();

我想正确的方法是删除这些行

adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");

在其他情况下,屏幕旋转会出现大问题。

你可以设置离屏限制(默认只有1个),所以片段只会被创建一次,不会被移除

viewPager.setOffscreenPageLimit(2);

我也拒绝理解这些行是什么意思

   completedTasks.add(new completedTasks(...);

是 CompletedTasks 片段吗?您要添加什么以及如何添加?

【讨论】:

我不能删除这些代码行,因为如果我这样做应用程序崩溃.. 加上行 completedtasks.add 是在已完成任务列表中添加新元素。 这是完成任务的代码。 code public completedTasks(String Taskname, String Practicename, String timeline, int taskimage,int categoryimage) this.Practicename = Practicename; this.Taskname = 任务名; this.timeline = 时间线; this.taskimage=taskimage; this.categoryimage=categoryimage; this.practiceimage=practiceimage; this.timeimage=timeimage; 【参考方案3】:

片段的 onCreate() 函数中没有这样的东西。

但它仍然落后,对吧?我认为问题在于您的布局过于繁重,因为您在 onCreateView() 中所做的唯一工作就是设置布局。

请检查您的图像是否具有很高的像素密度。这是一个最常见的错误。 Android系统需要时间将布局中的那些高像素图像转换为适合您的设备的较低像素密度,这需要时间并导致延迟。 其他原因可能是糟糕的布局层次结构。

【讨论】:

ì图像具有高分辨率,但在一个好的应用程序中,您应该使用具有良好清晰度的资源。版式怎么样,能详细点吗?帮我解决这个问题。我被困了一天【参考方案4】:

您应该从 FragmentActivity

扩展您的容器活动
public class MainActivity extends FragmentActivity


这是在片段之间非常快速的切换。

在 xml 布局中使用标签更好 单击选项卡或底部选项卡时显示、隐藏

//代码示例:

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fm.findFragmentById(fragment))
 .hide(fm.findFragmentById(activePage))
 .commit();

【讨论】:

以上是关于Android中切换标签片段之间的延迟的主要内容,如果未能解决你的问题,请参考以下文章

Android:BottomNavigationView第一个片段开关超级延迟

底部的android寻呼机标签条带走整个片段

在 Android Studio 的默认导航抽屉模板中使用按钮在片段之间切换

Android:在视图/活动/片段之间滑动切换

在Android Studio片段之间切换时地图片段不隐藏

Android:使用选项卡在不同片段之间切换