我正在编写我的第一个基于片段的应用程序并遇到了一些我无法使用 API 或 Stackoverflow 解决的严重问题。
我正在使用viewPager在两个列表之间滑动。每个列表都有一个标题按钮来创建一个新的列表元素(类似于原生的 android 警报应用程序)。该按钮当前返回一条错误消息以进行调试。
问题是:
- FragmentList A 返回 FragmentList B 的调试消息
FragmentList B 不返回调试消息
... // The main class public class DemoApp extends FragmentActivity implements ActionBar.TabListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); PageAdapter mPageAdapter = new PageAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mPageAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); for (int i = 0; i < mPageAdapter.getCount(); i++) { actionBar.addTab(actionBar.newTab().setText(mPageAdapter.getPageTitle(i)).setTabListener(this)); } } ...
我的自定义PageAdapter将创建两个列表 framgent 对象:
public class PageAdapter extends FragmentStatePagerAdapter {
private final int NUMBER_PAGES = 2;
public PageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return new FoodListFragment();
} else if (position == 1){
return new LocationListFragment();
} else {
throw new IllegalArgumentException("Invalid page position: " + position);
}
}
@Override
public int getCount() {
return NUMBER_PAGES;
}
...
}
FoodListFragment 被剪断(除调试输出外,其他列表看起来相似):
public class FoodListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
/*
* (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// add a list header with the button to create a new list item
View v = getActivity().getLayoutInflater().inflate(R.layout.list_header, null);
getListView().addHeaderView(v);
...
setListAdapter(getSomeAdapter());
// get the list header button
ImageButton createItem = (ImageButton) getActivity().findViewById(R.id.create_new_entry);
createItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(LOG_TAG, "onclick FoodListFragment");
}
});
}
主.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/wrapper"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".DemoApp" />
</LinearLayout>