ViewPager显示错误的片段

时间:2013-02-04 21:30:59

标签: android android-viewpager fragmentpageradapter

我试图找到解决我在网络上无处不在的问题的解决方案,但我还没有解决。 无论如何,这是我的问题。基本上当我启动我的TestWeekActivity(包含一个ViewPager)时,它会显示第一个插入的第二个片段/页面,当我滑到第二个时,我会看到第三个...换句话说它总是显示下一个或前一个片段/页面取决于滑动方向(左或右)。

将日志放到任何地方我明白每次刷卡片段时,我都会调用FragmentPagerAdapter.getItem(int)两次(我读到这种行为允许缓存近页)。但是我不明白为什么,当调用getItem方法时,也会调用onStart的相对片段方法,所以当我从第一页到第二页滑动时,由于第二次调用getItem方法,我看到了第三个片段。 我希望已经足够清楚了。

这是我的代码: TestWeekActivity

package com.bord.shutup;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class TestWeekActivity extends FragmentActivity implements TabListener {

private static final String TAG = "TestWeekActivity";

ActionBar mActionBar;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
ArrayList<Fragment> fragments;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_week);
    mActionBar = getActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // create the Fragment list
    fragments = new ArrayList<Fragment>();
    for (int i = 0; i < 7; i++) {
        Bundle args = new Bundle();
        args.putInt("day", i);
        Fragment f = DayFragment.newInstance(this);
        f.setArguments(args);
        fragments.add(f);
    }

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager(), fragments, getResources()
                    .getStringArray(R.array.day_of_week));

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager
            .setOnPageChangeListener(new           ViewPager.SimpleOnPageChangeListener() {

                @Override
                public void onPageSelected(int position) {
                    Log.d(TAG, "onPageSelected " + position);
                        mActionBar.setSelectedNavigationItem(position);
                }
            });

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        mActionBar.addTab(mActionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }
}

// ///////// TabListener stuff ////////
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

// ///////// Menu stuff ///////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_events, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        startActivity(new Intent(this, ChooserActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        return true;
    case R.id.add_event:
        startActivity(new Intent(this, CreateWeeklyEventActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        return true;
    }

    return false;
}

public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    private ArrayList<Fragment> fragments;
    private String[] titles;

    public SectionsPagerAdapter(FragmentManager fm,
            ArrayList<Fragment> fragments, String[] titles) {
        super(fm);
        this.fragments = fragments;
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int i) {
        Log.d(TAG, "getItem called " + i);
        return fragments.get(i);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
  }

}

DayFragment

package com.bord.shutup;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class DayFragment extends Fragment implements
    LoaderManager.LoaderCallbacks<Cursor>, MultiChoiceModeListener,
    OnItemClickListener {
private static final String TAG = "DayFragment"; // For debugging

ListView list_events;
SimpleCursorAdapter adapter;
private int day;

public static DayFragment newInstance(Context context) {
    DayFragment f = new DayFragment();
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate called");
    day = getArguments().getInt("day");
    Log.d(TAG, "fragment day: " + day);
    adapter = new SimpleCursorAdapter(getActivity(),                R.layout.row_weekly_event, null, new String[] {
                    EventsProvider.C_TITLE, EventsProvider.C_NOTE,
                    EventsProvider.C_START_TIME_HOUR,
                    EventsProvider.C_START_TIME_MINUTE,
                    EventsProvider.C_END_TIME_HOUR,
                    EventsProvider.C_END_TIME_MINUTE }, new     int[] {
                    R.id.title, R.id.note, R.id.hour_start_time,
                    R.id.minute_start_time, R.id.hour_end_time,
                    R.id.minute_end_time }, 0);
}

@Override
public void onStart() {
    super.onStart();
    int day = getArguments().getInt("day");
    Toast.makeText(getActivity(), "Day: " + day , Toast.LENGTH_SHORT).show();
}

// Associate a layout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView called " + day);
    return inflater.inflate(R.layout.activity_events, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.d(TAG, "onActivityCreated called " + day);
        Log.d(TAG, "set adapter " + day);
        list_events = (ListView) getActivity().findViewById(
                R.id.list_events);
        list_events.setAdapter(adapter);
        list_events.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        list_events.setMultiChoiceModeListener(this);
        list_events.setOnItemClickListener(this);
        getActivity().getSupportLoaderManager().initLoader(day, null, this);
}

// //////////    Loader callback   ///////////
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Log.d(TAG, "onCreateLoader called with args: " + id);
    switch (id) {
    case 0:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" + Calendar.MONDAY,
                null, EventsProvider.C_ID + " DESC");
    case 1:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" + Calendar.TUESDAY,
                null, EventsProvider.C_ID + " DESC");
    case 2:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null,
                EventsProvider.C_REPEAT_ON + "=" + Calendar.WEDNESDAY,
                null, EventsProvider.C_ID + " DESC");
    case 3:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" + Calendar.THURSDAY,
                null, EventsProvider.C_ID + " DESC");
    case 4:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" + Calendar.FRIDAY,
                null, EventsProvider.C_ID + " DESC");
    case 5:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" + Calendar.SATURDAY,
                null, EventsProvider.C_ID + " DESC");
    case 6:
        return new CursorLoader(getActivity(), EventsProvider.URI_T_WEEK,
                null, EventsProvider.C_REPEAT_ON + "=" +     Calendar.SUNDAY,
                null, EventsProvider.C_ID + " DESC");
    }
    return null;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    Log.d(TAG, "onLoadFinished called");
    adapter.swapCursor(cursor);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    Log.d(TAG, "onLoaderReset called");
    adapter.swapCursor(null);
}

}

提前感谢大家!

PS:我是新手,所以不要杀了我。 ;-) PPS:抱歉英语不好。

1 个答案:

答案 0 :(得分:1)

你不应该管理自己适配器会为你做的片段列表。从onCreate()中删除“创建片段列表”代码,并使用适配器的getItem()中的参数创建所请求页面片段的新实例。