我正在尝试在选择日期时刷新incomefrag
和expenditurefrag
。这就是我做的。它不会根据日期的变化而变化,但会在选择其他标签时更改。
调用片段的活动。由于代码超过200行只粘贴imp部分。
在此活动中,我选择了from和to日期。我希望incomefrag
和expenditurefrag
根据日期的变化而不是我在标签之间滑动时更改。
// extends AppComactActivity
private void setupViewPager(final ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new IncomeCatFrag(), "Income");
adapter.addFragment(new ExpenditureCatFrag(), "Expenditure");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
viewPager.getAdapter().notifyDataSetChanged();
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
SectionsPageAdapter
public class SectionsPageAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return mFragmentList.size();
}
}
这是我的incomefrag
。支出脆弱是相似的。
//extends Fragment
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.income_frag, container, false);
populate1(); // implemented later. searches through db to fill textviews etc.
return view;
}
答案 0 :(得分:0)
首先 在主活动中使用LocalBroadcastManager来扩展意图(当发生更改时)。
第二步: 在您选项卡式活动中注册广播接收器以接收来自主要活动的广播意图
第3步: 一旦您在选项卡式活动中收到广播,请在viewPager上设置与该片段相关的标签号: e,g viewPager.setCurrentItem(你的标签号)
MainActivity{ //send your broadcast when date changes
`Intent intent = new Intent("my_date_change_intent_name");
intent.putExtra("key", "dateChanged");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent); }`
TabbedActivity{//register your broadcast receiver and receive broadcasts
LocalBroadcastManager.getInstance(context).registerReceiver(MyReceiver,new IntentFilter("my_date_change_intent_name"))`;
BroadcastReceiver MyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null ) {
String str= intent.getStringExtra("key");
//Now set your tab number on viewPager
viewPager.setCurrentItem(YOUR_TAB_NUMBER)
}
}
}
});