我正在创建一个包含3个标签的应用程序。我从here获取了类似记事本的应用程序的代码,我想要的是将记事本放在选项卡内的片段中。我已经完成了这个,但每当我添加一个新笔记时,它都没有反映在标签中。我想我将不得不使用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;
}
}
答案 0 :(得分:0)
将此添加到SectionsPagerAdapter:
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
然后当你调用notifyDatasetChanged
时,适配器会认为所有页面都是新的并重新创建它们