如何更改TabLayout中当前片段的数据?

问题描述:

如何动态更改TabLayout中当前的fragment的内容。例如,如果当前片段上有一个列表,并且列表已更改,那么如何更新片段布局?如何更改TabLayout中当前片段的数据?

这里是默认生成的代码(从New选择>>Activity >>Tabbed Activity

public static class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    public PlaceholderFragment() { 
    } 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     TextView textView = (TextView) rootView.findViewById(R.id.section_label); 
     int areaID = getArguments().getInt(ARG_SECTION_NUMBER); 
     textView.setText(getString(R.string.section_format, areaID)); 
     return rootView; 
    } 
} 

/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a PlaceholderFragment (defined as a static inner class below). 
     return PlaceholderFragment.newInstance(position + 1); 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position) { 
      case 0: 
       return "SECTION 1"; 
      case 1: 
       return "SECTION 2"; 
      case 2: 
       return "SECTION 3"; 
     } 
     return null; 
    } 
} 
+0

你能不能对你有什么做更具体一点? – Mauker

+0

@Mauker我有一个ArrayList和ListView,当ArrayList被更改时,我想在当前片段上显示已更改的ArrayList –

你的问题是不是每说一个Fragment问题。由于您使用的是ListView,因此您可以使用预定义的适配器,也可以创建自己的自定义适配器。检查this answer of mine如何创建一个自定义的。

不过长话短说,你将需要:

  • 要么使用ArrayAdapter(作为似乎在this question),或创建自己的,如上所述在我的答案。

  • 每次修改适配器/集,调用该方法myAdapter#notifyDataSetChanged();