0

如何動態更改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 –

回答

1

你的問題是不是每說一個Fragment問題。由於您使用的是ListView,因此您可以使用預定義的適配器,也可以創建自己的自定義適配器。檢查this answer of mine如何創建一個自定義的。

不過長話短說,你將需要:

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

  • 每次修改適配器/集,調用該方法myAdapter#notifyDataSetChanged();