我是android新手。我有一个滑动标签布局和一个带片段的viewpager。我已经设置了这些之间的基本链接切换标签为5(即5个标签)问题是,在每个标签中,我想使用simplecursoradapter填充列表视图,为此我需要每个片段的位置所以我可以相应地填充它。我已经在片段适配器类中获得了位置,但我无法将其传递给主要活动。另外,如何在我的片段类中访问DBadapter以从数据库中填充listview?还是有其他方法可以做到这一点?以下是我的代码。任何帮助是极大的赞赏。提前谢谢。
public class myFragment extends Fragment{
private ListView mainList;
public static myFragment getInstance(int position){
myFragment MyFragment = new myFragment();
Bundle args = new Bundle();
args.putInt("position", position);
MyFragment.setArguments(args);
return MyFragment;
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_main_list,container, false);
mainList = (ListView)layout.findViewById(R.id.mainListView);
Bundle bundle = getArguments();
if(bundle!=null){
if(bundle.getInt("position")==0){
mainList.setBackgroundColor(getResources().getColor(R.color.primary500));
}
else if(bundle.getInt("position")==1){
mainList.setBackgroundColor(getResources().getColor(R.color.primary100));
}
else if(bundle.getInt("position")==2){
mainList.setBackgroundColor(getResources().getColor(R.color.primary700));
}
else if(bundle.getInt("position")==3){
mainList.setBackgroundColor(getResources().getColor(R.color.accent));
}
else if(bundle.getInt("position")==4){
mainList.setBackgroundColor(getResources().getColor(R.color.black));
}
}
return layout;
}
}
主要活动如下:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private ViewPager mPage;
private SlidingTabLayout mTabs;
DBadapter myDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
toolbar = (Toolbar)findViewById(R.id.app_bar);
mPage = (ViewPager)findViewById(R.id.pager);
mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
mFab = (FloatingActionButton)findViewById(R.id.fab);
setSupportActionBar(toolbar);
mPage.setAdapter(new myPagerAdapter(getSupportFragmentManager()));
mTabs.setViewPager(mPage);
}
public class myPagerAdapter extends FragmentPagerAdapter{
String[] tabs;
public myPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.tabs);
}
@Override
public Fragment getItem(int position) {
myFragment MyFragment = myFragment.getInstance(position);
return MyFragment;
}
@Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
@Override
public int getCount() {
return 5;
}
}
答案 0 :(得分:0)
使用此方法:
mPage.setOnPageChangeListener(new SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int pos) {
// pos is the position of fragment that app showing
});
<强>更新强>
在你的视图寻呼机适配器:
public Fragment getItem(int position) {
return new myFragment(position);
}
在你的片段类中:
public class myFragment extends Fragment{
private int pos
public void myFragment(int position){
this.pos = position;
}
// other code of your class