我正在编写我的第一个基于片段的应用,并遇到了一些我无法通过API或Stackoverflow解决的重大问题。
我正在使用 viewPager 在两个列表之间滑动。每个列表都有一个标题按钮,用于创建新的列表元素(类似于本机android警报应用程序)。该按钮当前返回错误消息以进行调试。
问题是:
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 snipped(除调试输出外,其他列表看起来很相似):
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");
}
});
}
main.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>
答案 0 :(得分:0)
我发现了这个错误。在每个列表中,我调用相同的标题视图和相同的标题按钮。无法明确指定onClick方法