我的应用程序从数据库 (ContentResolver) 加载数据并使用 ViewPager 在 ActionBar 中创建选项卡。以下代码按预期工作,但我希望有人查看我的代码。我需要知道它是否符合一般模式和做法?它需要改变吗?我能得到一些意见吗?
public class MainActivity extends SherlockFragmentActivity
{
private static final String TAG = MainActivity.class.getSimpleName();
TabAdapter tabAdapter;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabAdapter = new TabAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(tabAdapter);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
@Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
}
});
}
private class TabAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, LoaderManager.LoaderCallbacks<Cursor>
{
ArrayList<String> lists = new ArrayList<String>();
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
public TabAdapter(FragmentManager fragmentManager)
{
super(fragmentManager);
getSupportLoaderManager().initLoader(0, null, this);
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
@Override
public Fragment getItem(int arg0)
{
return fragments.get(arg0);
}
@Override
public int getCount()
{
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position)
{
return lists.get(position);
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1)
{
CursorLoader cursorLoader = new CursorLoader(
MainActivity.this,
TasksContentProvider.TaskLists.CONTENT_URI,
null,
null,
null,
null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c)
{
while (c.moveToNext())
{
String title = c.getString(c.getColumnIndex(TasksContentProvider.TaskLists.Columns.TITLE));
lists.add(title);
TaskListFragment fragment = new TaskListFragment();
Bundle bundle = new Bundle();
bundle.putInt("LIST_ID", c.getInt(c.getColumnIndex(TasksContentProvider.TaskLists.Columns._ID)));
fragment.setArguments(bundle);
fragments.add(fragment);
final ActionBar actionBar = getSupportActionBar();
actionBar.removeAllTabs();
for (int i = 0; i < getCount(); i++)
{
actionBar.addTab(actionBar.newTab().setText(getPageTitle(i)).setTabListener(this));
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> arg0)
{
}
}
}