我试图第一次实现ViewPager
,我能够让它工作但是我需要它能够做的是不时更新单个片段中的元素,我尝试在片段类中创建一个方法来执行此操作,但是此时它返回一个空指针,任何做过此操作的人都可以给我一些关于如何使其工作的提示吗?任何帮助都会有很长的路要谢!
这是我的片段活动和适配器:
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
MyFragment theFragment = (MyFragment) fragments.get(0);
theFragment.receiveUpdate();
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragment.newInstance("Fragment 1"));
fList.add(MyFragment.newInstance("Fragment 2"));
fList.add(MyFragment.newInstance("Fragment 3"));
return fList;
}
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
@Override
public int getCount() {
return this.fragments.size();
}
}
}
这是我的实际片段类:
public class MyFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
TextView messageTextView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
public void receiveUpdate() {
// Do something
messageTextView.setText("changed");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
messageTextView = (TextView) v.findViewById(R.id.textView);
messageTextView.setText(message);
ListView fragList = (ListView) v.findViewById(R.id.list);
String[] from = new String[] { "str", "str", "str", "str", "str",
"str", "str", "str", "str" };
ArrayAdapter adapter = new ArrayAdapter(v.getContext(),
android.R.layout.simple_list_item_1, from);
fragList.setAdapter(adapter);
return v;
}
}