我正在创建一个包含 3 个选项卡的应用程序。我从 here 中获取了类似记事本应用程序的代码,我想要的是将记事本放在选项卡内的 fragment 中。我已经这样做了,但是每当我添加新注释时,它都不会反射(reflect)在选项卡中。我想我将不得不使用 notifyDataSetChanged()
但我不知道在哪里可以使用它。一些帮助将不胜感激。
我在选项卡中放了一个 FAB。当我单击它时,应用会转到 DisplayNote
,我可以在其中输入笔记标题和内容,就像在原始应用中一样。我已经确认,当我点击“保存”时,便条已保存,但选项卡未显示。
这是我的 MainActivity 的相关代码:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
}
这是适配器的代码:
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab 1";
case 1:
return "Tab 2";
case 2:
return "Notes";
default:
return null;
}
}
这是第三个选项卡的代码:
public class Tab3Notes extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mynotes, container, false);
FloatingActionButton add_note;
add_note = (FloatingActionButton) rootView.findViewById(R.id.add_note_button);
add_note.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getContext(), DisplayNote.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
return rootView;
}
}
最佳答案
将此添加到您的 SectionsPagerAdapter:
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
然后当你调用notifyDatasetChanged
时,适配器会认为所有页面都是新的并重新创建它们
关于android - 如何使用新数据更新 TabLayout 中的 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226993/