1

我正在使用ViewPager我的应用程序将一系列列表放在水平滚动条中。但是,当我开始横向滚动并再次返回时,我之前访问过的列表片段是空的。这应该是我编写的加载器重新加载内容的时刻(我对片段和加载器都是新手)。

我已经看到了一些相关的问题,但我不知道如何将它们应用于我的情况。我发现当我用随机 int 替换持有者片段中的 mLayoutID 时,这个示例有效,但是当我这样做时,事情自然会停止工作(比如改变方向)。但它应该对这个问题说些什么。

基本上,listfragment 只是在初始加载后清空并保持为空。

这是我的“持有人”片段:

public final class SceduleFragment extends Fragment {

    private static final String KEY_LAYOUT = "SceduleFragment:LayoutID";
    private static final String LOG_TAG = "SceduleFragment";

    private int mWeekNumber;
    private int mLayoutID;

    public static SceduleFragment newInstance(String content, int contentID) {
        SceduleFragment fragment = new SceduleFragment();
        fragment.mWeekNumber = contentID;
        fragment.mLayoutID = Integer.parseInt((Integer.toString(Config.WK_PREFIX) + Integer.toString(contentID)));

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_LAYOUT)) {
            mLayoutID = savedInstanceState.getInt(KEY_LAYOUT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setGravity(Gravity.TOP);
        layout.setPadding(makeDP(5), makeDP(5), makeDP(5), makeDP(5));

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(layoutParams);

        LinearLayout innerLayout = new LinearLayout(getActivity());
        innerLayout.setBackgroundResource(R.drawable.scd_layout_bg);
        LinearLayout.LayoutParams scrollParams = new LinearLayout.LayoutParams(
                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        innerLayout.setGravity(Gravity.CENTER);
        innerLayout.setLayoutParams(scrollParams);
        layout.addView(innerLayout);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_LAYOUT)) {
            mLayoutID = savedInstanceState.getInt(KEY_LAYOUT);
        }

        Random rand = new Random();
        //mLayoutID = rand.nextInt(2000);

        innerLayout.setId(mLayoutID);  
        Log.i(LOG_TAG, "ID for next WeekListFragment " +  Integer.toString(mLayoutID));        

        if (getFragmentManager().findFragmentById(mLayoutID) == null) {         
            WeekFragment weekFragment = new WeekFragment(mWeekNumber);
            getFragmentManager().beginTransaction().add(mLayoutID, weekFragment).commit();
        }

        return layout;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_LAYOUT, mLayoutID);
    }

    private int makeDP(int number){      
        final float scale = this.getResources().getDisplayMetrics().density;
        number = (int) (number * scale + 0.5f);
        return number;
    }
}

这是在里面创建列表的 ListFragment:

public class WeekFragment extends ListFragment implements
        LoaderManager.LoaderCallbacks<Cursor> {

    private String LOG_TAG = "WeekFragment";
    private static final String KEY_WEEKNR = "SceduleFragment:WeekNumber";

    protected Activity mActivity;
    protected Cursor mCursor;
    protected SceduleDataSource mDataSource;

    private int mWeekNumber;

    private static final int SCEDULEITEMS_LIST_LOADER = 0x0577; 
    private static Typeface fontOswaldLight;

    private SceduleItemsCursorAdapter mAdapter;

    public WeekFragment() { }

    public WeekFragment(int weekNumber) {
        this.mWeekNumber = weekNumber;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        LoaderManager.enableDebugLogging(true);

        mActivity = getActivity();
        mDataSource = new SceduleDataSource(mActivity);
        fontOswaldLight = Typeface.createFromAsset(mActivity.getAssets(),
                "Oswald-Light.otf");

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_WEEKNR)) {
            mWeekNumber = savedInstanceState.getInt(KEY_WEEKNR);
            Log.i(LOG_TAG, "Resorting to savestate.");
        } else {
            Log.i(LOG_TAG, "Saved state was null");

            getLoaderManager().initLoader(SCEDULEITEMS_LIST_LOADER, null, this);
            mAdapter = new SceduleItemsCursorAdapter(mActivity,
                    R.layout.scd_lesson_list_item, mCursor, new String[] {
                            SceduleItems.SCEDULE_DATE,
                            SceduleItems.SCEDULE_LESSONNAME,
                            SceduleItems.SCEDULE_BEGIN, SceduleItems.SCEDULE_ROOM,
                            SceduleItems.SCEDULE_TEACHER,
                            SceduleItems.SCEDULE_CLASS }, new int[] {
                            R.id.textDayTitle, R.id.textLessonName,
                            R.id.textLessonTime, R.id.textLessonRoom,
                            R.id.textLessonTeacher, R.id.textLessonClass }, 0);

            Log.i(LOG_TAG, "Filled WeekListFragment");

            setListAdapter(mAdapter);       
        }        
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_WEEKNR, mWeekNumber);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ColorDrawable divider = new ColorDrawable(this.getResources().getColor(
                R.color.LightGrey));
        ListView listView = getListView();
        listView.setDivider(divider);
        listView.setDividerHeight(makeDP(1));
        listView.setLongClickable(true);
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View v,
                    int position, long id) {

                Cursor lessonCursor = (Cursor) getListView().getItemAtPosition(
                        position);
                showLessonDialog(lessonCursor);
                return true;
            }
        });
    }

    public void showLessonDialog(Cursor lessonCursor) {

        String dialogTitle = lessonCursor.getString(2);

        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(
                mActivity);
        AlertDialog lessonDialog;

        LayoutInflater inflater = (LayoutInflater) mActivity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View dialogLayout = inflater.inflate(R.layout.dlg_lesson_item, null);

        TextView textLessonName = (TextView) dialogLayout
                .findViewById(R.id.textLessonName);
        textLessonName.setText(lessonCursor.getString(2));
        TextView textLessonTime = (TextView) dialogLayout
                .findViewById(R.id.textLessonTime);
        textLessonTime.setText(lessonCursor.getString(6) + " - "
                + lessonCursor.getString(7));
        TextView textLessonRoom = (TextView) dialogLayout
                .findViewById(R.id.textLessonRoom);
        textLessonRoom.setText(lessonCursor.getString(8));
        TextView textLessonTeacher = (TextView) dialogLayout
                .findViewById(R.id.textLessonTeacher);
        textLessonTeacher.setText(lessonCursor.getString(9));
        TextView textLessonClass = (TextView) dialogLayout
                .findViewById(R.id.textLessonClass);
        textLessonClass.setText(lessonCursor.getString(10));

        dialogBuilder.setView(dialogLayout).setNeutralButton("Sluit",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

        WebView webView = new WebView(mActivity);
        webView = (WebView) dialogLayout.findViewById(R.id.adWebView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        String adHtml = "<html><body>"
                + "<style type='text/css'>body{margin: 0;padding: 0}</style>"
                + "<script type'text/javascript'>"
                + "var admob_vars = {"
                + "pubid: 'xxxxxxxxxx', "
                + "bgcolor: '000000', "
                + "text: 'FFFFFF', "
                + "test: true };"
                + "</script>"
                + "<script type='text/javascript' src='http://mmv.admob.com/static/iphone/iadmob.js'></script></body></html>";
        webView.loadData(adHtml, "text/html", "UTF-8");

        lessonDialog = dialogBuilder.create();
        lessonDialog.setTitle(dialogTitle);
        lessonDialog.show();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        String dateConverter = "substr(" + SceduleItems.SCEDULE_DATE + ",7)||"
                + "substr(" + SceduleItems.SCEDULE_DATE + ",4,2)||" + "substr("
                + SceduleItems.SCEDULE_DATE + ",1,2)||" + "substr("
                + SceduleItems.SCEDULE_BEGIN + ",1,2)||" + "substr("
                + SceduleItems.SCEDULE_BEGIN + ",4,2)";

        CursorLoader cursorLoader = new CursorLoader(getActivity(),
                ONTTContentProvider.CONTENT_URI, mDataSource.allSceduleColumns,
                SceduleItems.SCEDULE_WEEKCODE + " like '" + mWeekNumber + "'",
                null, dateConverter + " ASC");

        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        mAdapter.swapCursor(cursor);
        Log.i(LOG_TAG, "Finished with loading week " + Integer.toString(mWeekNumber));
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }

    private int makeDP(int number) {
        final float scale = this.getResources().getDisplayMetrics().density;
        number = (int) (number * scale + 0.5f);
        return number;
    }

    public class SceduleItemsCursorAdapter extends SimpleCursorAdapter {

        private LayoutInflater layoutInflater;
        private int layout;

        public SceduleItemsCursorAdapter(Context context, int layout, Cursor cursor,
                String[] from, int[] to, int flags) {

            super(context, layout, cursor, from, to, flags);

            this.layout = layout;
            layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View view = layoutInflater.inflate(layout, parent, false);
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            String viewID = Config.SI_PREFIX + cursor.getString(0);

            view.setId(Integer.parseInt(viewID));
            LinearLayout dayHeader = (LinearLayout) view.findViewById(R.id.layoutDayTitle);
            TextView dayTitle = (TextView) view.findViewById(R.id.textDayTitle);
            TextView lessonName = (TextView) view.findViewById(R.id.textLessonName);
            TextView lessonTime = (TextView) view.findViewById(R.id.textLessonTime);
            TextView lessonRoom = (TextView) view.findViewById(R.id.textLessonRoom);
            TextView lessonTeacher = (TextView) view.findViewById(R.id.textLessonTeacher);
            TextView lessonClass = (TextView) view.findViewById(R.id.textLessonClass);

            lessonName.setText(cursor.getString(2));
            lessonTime.setText(cursor.getString(6) + " - " + cursor.getString(7));
            lessonRoom.setText(cursor.getString(8));
            lessonTeacher.setText(cursor.getString(9));
            lessonClass.setText(cursor.getString(10));

            String thisDate = cursor.getString(5);
            String prevDate = null;

            if (cursor.getPosition() > 0 && cursor.moveToPrevious()) {
                prevDate = cursor.getString(5);
                cursor.moveToNext();
            }

            if (prevDate == null || !prevDate.equals(thisDate)) {
                dayHeader.setVisibility(View.VISIBLE);

                String dayName = Config.Days[Integer.parseInt(cursor.getString(3))];            
                dayName += " " + cursor.getString(5);
                dayTitle.setText(dayName);
                dayTitle.setTypeface(fontOswaldLight);
            } else {
                dayHeader.setVisibility(View.GONE);
            }

            if((Config.SI_PREFIX + ONTTShowScedule.upcomingItemID).equals(viewID)) {
                int redColor = getResources().getColor(R.color.DarkRed);

                lessonName.setTextColor(redColor);
                lessonTime.setTextColor(redColor);
                lessonRoom.setTextColor(redColor);
                lessonTeacher.setTextColor(redColor);
                lessonClass.setTextColor(redColor);
            }
        }
    }
}
4

1 回答 1

0

我在这里找到了导致我的问题的原因:

父片段不显示子 ViewPager

“你不能将碎片嵌套在碎片中。”

于 2012-06-25T12:12:54.920 回答