我想定期根据我从互联网下载的数据更新片段的显示。我创建了一个计时器和可运行对象,以周期性地检索此数据,以及一个在片段内更新该数据的方法,但我似乎无法弄清如何从活动获取对片段的引用以便进行更新。
我有以下代码,这主要是由ADT的Android项目向导生成的:
我有以下代码,这主要是由ADT的Android项目向导生成的:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(tag, "onCreate()::Entering...");
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
以下是用于创建选项卡的代码:
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.
switch (position)
{
case FRAG1_POS:
return Fragment1.newInstance();
case FRAG2_POS:
return Fragment2.newInstance();
default:
return null;
}
}
我尝试使用了这个解决方案:
如何从Activity更改Fragment的TextView文本
但是我没有fragment ID,我能创建标签吗?如果可以,那么在这种情况下我该如何做?其他SO帖子提到了Bundles,但我在创建Fragment时不会发送数据;我希望在数据从Activity变得可用时定期更新Fragment。
if (fragment instanceof YourFragment)
。 - Szymon