ViewPager

时间:2015-07-20 16:59:28

标签: android android-fragments android-viewpager pagerslidingtabstrip

我用于我的Android应用PagerSlidingTabStripMaterial Navigation Drawer库。我正在观看ViewPager的奇怪行为 - 当我第一次打开它时,它正常工作,但我再次打开它,ViewPager是空的,没有适配器。

MainActivity:

public class MainActivity extends AppCompatActivity {

    private Drawer drawer;
    private int lastSelection;
    private BroadcastReceiver mRegistrationBroadcastReceiver;

    private boolean isClickedByUser = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = new DrawerBuilder().withActivity(MainActivity.this)
                .withToolbar(toolbar).addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.name1)
                                .withIcon(R.drawable.icon1),
                        new PrimaryDrawerItem()
                                .withName(R.string.name2)
                                .withIcon(R.drawable.icon2))
                .withOnDrawerItemClickListener(
                        new Drawer.OnDrawerItemClickListener() {
                            @Override
                            public boolean onItemClick(AdapterView<?> adapterView, View view,
                                                       int position, long id,
                                                       IDrawerItem iDrawerItem) {
                                switch (position) {
                                    case 0:
                                        setTitle(R.string.title1);
                                        break;
                                    case 1:
                                        setTitle(R.string.title2);
                                        break;
                                }

                                FragmentManager fManager = getSupportFragmentManager();
                                FragmentTransaction transaction = fManager.beginTransaction();
                                transaction.replace(R.id.container, PlaceholderFragment.newInstance(
                                        position)).commitAllowingStateLoss();

                                lastSelection = position;
                                return false;
                            }
                        })
                .build();


        drawer.setSelection(0);
    }

    @Override
    public void onBackPressed() {
        if (drawer != null && drawer.isDrawerOpen()) {
            drawer.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
        drawer.setSelection(lastSelection);
    }

}

PlaceholderFragment,在ViewPager中完成:

public class PlaceholderFragment extends Fragment {

    private static final String ID = "id";

    private int id;

    public static PlaceholderFragment newInstance(int id) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getInt(ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = null;

        switch (id) {
            case 0:
                rootView = inflater.inflate(R.layout.view1, container, false);
                break;
            case 1:
                rootView = inflater.inflate(R.layout.tabs, container, false);

                ViewPager pager = (ViewPager) rootView.findViewById(R.id.viewPager);
                pager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager()));

                PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
                tabs.setViewPager(pager);
                tabs.setShouldExpand(true);
                tabs.setIndicatorColorResource(R.color.tab_indicator_color);
                tabs.setTextColorResource(R.color.tab_text_color);
                break;
            default:
                break;
        }

        return rootView;
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        private int[] titlesResIds = { R.string.title1, R.string.title2 };

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public int getCount() {
            return titlesResIds.length;
        }

        @Override
        public Fragment getItem(int position) {
            return TabFragment.newInstance(position);
        }
    }

}

TabFragment:

public class TabFragment extends ListFragment {

    private static final String ID = "id";
    private int id;

    public static TabFragment newInstance(int id) {
        TabFragment fragment = new TabFragment();
        Bundle args = new Bundle();
        args.putInt(ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    public TabFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getInt(ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... params) {
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url("http://host/")
                        .build();

                String result = null;
                try {
                    Response response = client.newCall(request).execute();
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String response) {
                super.onPostExecute(response);
                Gson gson = new Gson();
                JsonReader reader = new JsonReader(new StringReader(response));
                reader.setLenient(true);

                ArrayList<Message> messages = gson.fromJson(reader,
                        new TypeToken<ArrayList<Message>>(){}.getType());

                int i = messages.size() - 1;

                while (i != -1) {
                    if (messages.get(i).getType() != id)
                        messages.remove(i);

                    i--;
                }

                ArrayAdapter adapter = new MyListAdapter(messages);
                setListAdapter(adapter);
            }
        };

        asyncTask.execute();

        return inflater.inflate(R.layout.fragment, container, false);
    }

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

        Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
        startActivity(messageIntent);
    }

    private class MyListAdapter extends ArrayAdapter {

        private Context context = getActivity();
        private ArrayList<Message> messages;

        public MyListAdapter(ArrayList<Message> messages) {
            super(getActivity(), R.layout.list_adapter);
            this.messages = messages;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.list_adapter, parent, false);

                holder = new ViewHolder();
                holder.imageIcon = (ImageView) convertView.findViewById(R.id.list_icon);
                holder.textDatetime = (TextView) convertView.findViewById(R.id.list_text_datetime);
                holder.textPrimary = (TextView) convertView.findViewById(R.id.list_text_primary);
                holder.textSecondary = (TextView) convertView.findViewById(R.id.list_text_secondary);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Message message = messages.get(position);

            long timestamp = message.getTimestamp() * 1000;
            Date date = new Date(timestamp);
            String datetime = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US).format(date);

            holder.imageIcon.setImageResource(message.getIcon() == 0 ?
                    R.drawable.icon1 :
                    R.drawable.icon2);
            holder.textDatetime.setText(datetime);
            holder.textPrimary.setText(message.getTitle());
            holder.textSecondary.setText(message.getMessage());

            return convertView;
        }

        private class ViewHolder {
            ImageView imageIcon;
            TextView textDatetime;
            TextView textPrimary;
            TextView textSecondary;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我已经决定了我的问题。我在我的getChildFragmentManager()中插入方法PlaceholderFragment,就像在这个答案中一样 - How set ViewPager inside a Fragment