我是Android编程的新手,我试图使用带有片段的gridviewpager。我的代码是:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
final Resources res = getResources();
GridViewPager pager = (GridViewPager) findViewById(R.id.gridpager);
pager.setOnApplyWindowInsetsListener(new OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
// Adjust page margins:
// A little extra horizontal spacing between pages looks a bit
// less crowded on a round display.
final boolean round = insets.isRound();
int rowMargin = res.getDimensionPixelOffset(R.dimen.page_row_margin);
int colMargin = res.getDimensionPixelOffset(round ?
R.dimen.page_column_margin_round : R.dimen.page_column_margin);
pager.setPageMargins(rowMargin, colMargin);
// GridViewPager relies on insets to properly handle
// layout for round displays. They must be explicitly
// applied since this listener has taken them over.
pager.onApplyWindowInsets(insets);
return insets;
}
});
// MyPagerAdapter adapter=new MyPagerAdapter();
pager.setAdapter(new MyPagerAdapter(Activity.getFragmentManager()));
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return SecondFragment.newInstance("SecondFragment, Instance 2");
default: return SecondFragment.newInstance("SecondFragment, Default");
}
}
@Override
public int getCount() {
return 3;
}
}
}
我崩溃了一些简洁。错误在这一行:
pager.setAdapter(new MyPagerAdapter(Activity.getFragmentManager()));
这将返回错误:
非静态方法' getFragmentManager()'无法从静态上下文引用
但我不知道代码中的静态内容。我已经尝试将我能想到的所有内容分配给变量,但仍然无法得到它。谢谢你的帮助。
答案 0 :(得分:1)
Activity
是一个类的名称。通过声明Activity.getFragmentManager()
,您试图在类本身而不是该类的特定实例上调用方法。
在您的情况下,您根本不需要Activity.
部分 - 只需致电getFragmentManager()
本身:
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));