Android: ListFragment всегда показывает список инициализации на фоне - PullRequest
1 голос
/ 25 августа 2011

Я пытаюсь реализовать три ListFragments в основной деятельности. Третий список является подсписком второго, а второй - подсписком первого. Я начал с примера FragmentLayout из демонстрации API. После того как я добавил эти три ListFragments, я мог видеть, что всякий раз, когда я делал выделение, я всегда вижу, что на экране сначала отображается список с первыми выделениями (все ListFragments), а затем поверх него рисуется новый ListFragment. Кроме того, эти первые выборы (NFL, NFC West, 49ers) всегда подсвечиваются, даже если выбрана другая запись. Есть идеи? Спасибо!

Из кода ниже, я всегда вижу это на заднем плане:

NFL NFC West 49ers MLB NFC East Seahawks АФК Вест Рамс Кардиналы

Вот код:

public class FragmentLayout2 extends Activity {

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

        setContentView(R.layout.main);
    }


    /**
     * This is a secondary activity, to show what the user has selected
     * when the screen is not large enough to show it all in one activity.
     */

    public static class DetailsActivity extends Activity {

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

            if (getResources().getConfiguration().orientation
                    == Configuration.ORIENTATION_LANDSCAPE) {
                // If the screen is now in landscape mode, we can show the
                // dialog in-line with the list so we don't need this activity.
                finish();
                return;
            }
/*
            if (savedInstanceState == null) {
                // During initial setup, plug in the details fragment.
                DetailsFragment details = new DetailsFragment();
                details.setArguments(getIntent().getExtras());
                getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
            }
            */
        }
    }


    /**
     * This is the "top-level" fragment, showing a list of items that the
     * user can pick.  Upon picking an item, it takes care of displaying the
     * data to the user as appropriate based on the current UI layout.
     */

    public static class TitlesFragment0 extends ListFragment {
        boolean mDualPane0;
        int mCurCheckPosition0 = 0;
        int mShownCheckPosition0 = -1;
        TitlesFragment1 tf1 = null;

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

            // Populate list with our static array of titles.
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES0));

            // Check to see if we have a frame in which to embed the details
            // fragment directly in the containing UI.
            View detailsFrame = getActivity().findViewById(R.id.titles1);
            mDualPane0 = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                // Restore last state for checked position.
                mCurCheckPosition0 = savedInstanceState.getInt("curChoice0", 0);
                mShownCheckPosition0 = savedInstanceState.getInt("shownChoice0", -1);
            }

            if (mDualPane0) {
                // In dual-pane mode, the list view highlights the selected item.
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                // Make sure our UI is in the correct state.
                showDetails(mCurCheckPosition0);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("curChoice0", mCurCheckPosition0);
            outState.putInt("shownChoice0", mShownCheckPosition0);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            showDetails(position);
        }

        /**
         * Helper function to show the details of a selected item, either by
         * displaying a fragment in-place in the current UI, or starting a
         * whole new activity in which it is displayed.
         */
        void showDetails(int index) {
            mCurCheckPosition0 = index;

            if (mDualPane0) {
                // We can display everything in-place with fragments, so update
                // the list to highlight the selected item and show the data.
                getListView().setItemChecked(index, true);

                if (mShownCheckPosition0 != mCurCheckPosition0) {
                    // If we are not currently showing a fragment for the new
                    // position, we need to create and install a new one.
                    //TitlesFragment1 df = TitlesFragment1.newInstance(index);
                    if (tf1==null)
                    {

                    }
                    else
                    {
                        FragmentTransaction ft2 = getFragmentManager().beginTransaction();
                        ft2.remove(tf1);
                        ft2.commit();
                    }
                    tf1 = TitlesFragment1.newInstance(index);
                    // Execute a transaction, replacing any existing fragment
                    // with this one inside the frame.
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.titles1, tf1);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
                    mShownCheckPosition0 = index;
                }

            } else {
                // Otherwise we need to launch a new activity to display
                // the dialog fragment with selected text.
                Intent intent = new Intent();
                intent.setClass(getActivity(), DetailsActivity.class);
                intent.putExtra("index0", index);
                startActivity(intent);
            }
        }
    }


    public static class TitlesFragment1 extends ListFragment {
        boolean mDualPane1;
        int mCurCheckPosition1 = 0;
        int mShownCheckPosition1 = -1;
        TitlesFragment2 tf2 = null;

        public static TitlesFragment1 newInstance(int index) {
            TitlesFragment1 f = new TitlesFragment1();

            // Supply index input as an argument.
            Bundle args = new Bundle();
            args.putInt("index0", index);
            f.setArguments(args);

            return f;
        }


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

            int upIndex = 0;
            if (getArguments() != null)
                upIndex = getArguments().getInt("index0", 0);

            // Populate list with our static array of titles.
            if (upIndex==0)
                setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES00));
            else
                setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES01));

            // Check to see if we have a frame in which to embed the details
            // fragment directly in the containing UI.
            View detailsFrame = getActivity().findViewById(R.id.titles2);
            mDualPane1 = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                // Restore last state for checked position.
                mCurCheckPosition1 = savedInstanceState.getInt("curChoice1", 0);
                mShownCheckPosition1 = savedInstanceState.getInt("shownChoice1", -1);
            }

            if (mDualPane1) {
                // In dual-pane mode, the list view highlights the selected item.
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                // Make sure our UI is in the correct state.
                showDetails(mCurCheckPosition1);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("curChoice1", mCurCheckPosition1);
            outState.putInt("shownChoice1", mShownCheckPosition1);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            showDetails(position);
        }

        /**
         * Helper function to show the details of a selected item, either by
         * displaying a fragment in-place in the current UI, or starting a
         * whole new activity in which it is displayed.
         */
        void showDetails(int index) {
            mCurCheckPosition1 = index;

            int upIndex = 0;
            if (getArguments() != null)
                upIndex = getArguments().getInt("index0", 0);

            if (mDualPane1) {
                // We can display everything in-place with fragments, so update
                // the list to highlight the selected item and show the data.
                getListView().setItemChecked(index, true);

                if (mShownCheckPosition1 != mCurCheckPosition1) {
                    // If we are not currently showing a fragment for the new
                    // position, we need to create and install a new one.
                    //TitlesFragment2 df = TitlesFragment2.newInstance(upIndex, index);
                    if (tf2==null)
                    {

                    }                   
                    else
                    {
                        FragmentTransaction ft2 = getFragmentManager().beginTransaction();
                        ft2.remove(tf2);
                        ft2.commit();

                    }
                    tf2 = TitlesFragment2.newInstance(upIndex, index);
                    // Execute a transaction, replacing any existing fragment
                    // with this one inside the frame.
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.titles2, tf2);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();

                    mShownCheckPosition1 = index;
                }

            } else {
                // Otherwise we need to launch a new activity to display
                // the dialog fragment with selected text.
                Intent intent = new Intent();
                intent.setClass(getActivity(), DetailsActivity.class);
                intent.putExtra("index0", upIndex);
                intent.putExtra("index1", index);
                startActivity(intent);
            }
        }
    }

    public static class TitlesFragment2 extends ListFragment {
        boolean mDualPane2;
        int mCurCheckPosition2 = 0;
        int mShownCheckPosition2 = -1;

        public static TitlesFragment2 newInstance(int upIndex, int index) {
            TitlesFragment2 f = new TitlesFragment2();

            // Supply index input as an argument.
            Bundle args = new Bundle();
            args.putInt("index0", upIndex);
            args.putInt("index1", index);
            f.setArguments(args);

            return f;
        }


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

            int upIndex0 = 0;
            int upIndex1 = 0;
            if (getArguments() != null)
            {
                upIndex0 = getArguments().getInt("index0", 0);
                upIndex1 = getArguments().getInt("index1", 0);
            }

            if (upIndex0 == 0)
            {
                if (upIndex1 == 0)
                    // Populate list with our static array of titles.
                    setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES000));
                else if (upIndex1 == 1)
                    setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES001));
                else
                    setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES002));
            }
            else
            {
                setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES010));
            }
            // Check to see if we have a frame in which to embed the details
            // fragment directly in the containing UI.
            View detailsFrame = getActivity().findViewById(R.id.titles2);
            mDualPane2 = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                // Restore last state for checked position.
                mCurCheckPosition2 = savedInstanceState.getInt("curChoice2", 0);
                mShownCheckPosition2 = savedInstanceState.getInt("shownChoice2", -1);
            }

            if (mDualPane2) {
                // In dual-pane mode, the list view highlights the selected item.
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                // Make sure our UI is in the correct state.
                showDetails(mCurCheckPosition2);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("curChoice2", mCurCheckPosition2);
            outState.putInt("shownChoice2", mShownCheckPosition2);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            showDetails(position);
        }

        /**
         * Helper function to show the details of a selected item, either by
         * displaying a fragment in-place in the current UI, or starting a
         * whole new activity in which it is displayed.
         */
        void showDetails(int index) {
            mCurCheckPosition2 = index;
            int upIndex0 = 0;
            int upIndex1 = 0;
            if (getArguments() != null)
            {
                upIndex0 = getArguments().getInt("index0", 0);
                upIndex1 = getArguments().getInt("index1", 0);
            }

            if (mDualPane2) {
                // We can display everything in-place with fragments, so update
                // the list to highlight the selected item and show the data.
                getListView().setItemChecked(index, true);

            } else {
                // Otherwise we need to launch a new activity to display
                // the dialog fragment with selected text.
                Intent intent = new Intent();
                intent.setClass(getActivity(), DetailsActivity.class);
                intent.putExtra("index0", upIndex0);
                intent.putExtra("index1", upIndex1);
                intent.putExtra("index2", index);
                startActivity(intent);
            }
        }
    }

}

Вот константы:

public final class Shakespeare {
    /**
     * Our data, part 1.
     */
    public static final String[] TITLES0 = 
    {
            "NFL",   
            "MLB"
    };

    public static final String[] TITLES00 = 
    {
            "NFC West",   
            "NFC East",
            "AFC West"
    };

    public static final String[] TITLES01 = 
    {
            "No Groups"
    };

    public static final String[] TITLES000 = 
    {
            "49ers",   
            "Seahawks",
            "Rams",       
            "Cardinals"
    };

    public static final String[] TITLES001 = 
    {
            "Cowboys",   
            "Giants",
            "Egales",       
            "Redskins"
    };

    public static final String[] TITLES002 = 
    {
            "Chargers",   
            "Chiefs",
            "Broncos",       
            "Raiders"
    };

    public static final String[] TITLES010 = 
    {
            "No members"
    };
}

1 Ответ

0 голосов
/ 25 августа 2011

Я обнаружил, что мне не нужно динамически добавлять эти списочные фрагменты, поскольку они уже указаны в файле XML. Все, что мне нужно сделать, это найти ListFragment:

TitlesFragment2 tf2 = (TitlesFragment2) getFragmentManager (). FindFragmentById (R.id.titles2);

и затем обновите список.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...