从fragmentB按下后退按钮后,Android片段无法恢复ViewPager

时间:2014-11-06 18:52:31

标签: android android-fragments android-viewpager back-stack

总结标题中的问题并不容易......

首先,有一个代表问题的图片:http://nicolas-barroso.legtux.org/bookin_stackoverflow.jpg

我有一个初始片段,当我们按下OK按钮时,EdiText及其内容会在同一片段中更新它下面的ViewPager。(所以不创建新片段)。

当我点击ViewPager元素时,会创建一个包含元素信息的新片段。

但是当我想回到之前的片段时,带有文本内容和OK按钮的EditText就在这里,但不是Viewpager。如果我再次按下OK按钮,则会将viewPager加载到我单击OK时的相同位置。

ViewPager使用简单的PagerAdapter。我尝试使用FragmentPagerAdapter因为我搜索了一些解决方案,但我遇到了很多问题,我无法解决这些问题。

下面是初始代码

public class SearchBookFragment extends Fragment {

    private View view;
    private List<Book> bookList;

    public static SearchBookFragment newInstance() {

        SearchBookFragment fragment = new SearchBookFragment();
        return fragment;
    }

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

        view = inflater.inflate(R.layout.fragment_search_book, container, false);

        final EditText searchField = (EditText) view.findViewById(R.id.searchField);
        searchField.clearFocus();

        final ImageButton validationSearch = (ImageButton) view.findViewById(R.id.validationSearch);

        validationSearch.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                           InputMethodManager.HIDE_NOT_ALWAYS);

                String searchWords = searchField.getText().toString();
                bookList = new ArrayList<Book>();

                String jsonBooks;
                try {
                    jsonBooks = new RetreiveJsonTask().execute("q="+ Uri.encode(searchWords)).get();
                    bookList = JSONFactory.createBookList(jsonBooks);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                };

                ViewPager mViewpager = (ViewPager) view.findViewById(R.id.book_viewpager);
                ViewPagerAdapterBooksResult pagerAdapterLooks = new ViewPagerAdapterBooksResult(getActivity(), bookList);
                mViewpager.setAdapter(pagerAdapterLooks);
            }
        });

        super.onCreate(savedInstanceState);
        return view;
    }
}

ViewPager的代码

public class ViewPagerAdapterBooksResult extends PagerAdapter{

    private Context context;
    private LayoutInflater inflater;
    private List<Book> books;


    public ViewPagerAdapterBooksResult(Context context, List<Book> books) {
        this.context = context;
        this.books = books;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        final int vpposition = position;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.adapter_viewpager_books_result, container, false); 

        if(this.books.get(position).getThumbnail() != null){
            final LoaderImageView image = (LoaderImageView) itemView.findViewById(R.id.book_image);
            image.setImageDrawable(books.get(position).getThumbnail() + "&zoom=0");
        }

        TextView bookTitle = (TextView) itemView.findViewById(R.id.book_title);             
        bookTitle.setText(new StringBuilder().append(books.get(position).getTitle()));

        TextView bookAuthor = (TextView) itemView.findViewById(R.id.book_author);

        bookAuthor.setText(new StringBuilder().append(books.get(position).getAuthors().get(0)));



        TextView bookDate = (TextView) itemView.findViewById(R.id.book_date);               
        bookDate.setText(new StringBuilder().append(books.get(position).getDate()));


        ((ViewPager) container).addView(itemView);


        itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Book selectedBook = books.get(vpposition);
                BookDetailsFragment bookDetailFragment = BookDetailsFragment.newInstance(selectedBook.getThumbnail(), selectedBook.getTitle(), selectedBook.getAuthors(), selectedBook.getDate(), selectedBook.getDescription(),selectedBook.getPublisher());
                ((FragmentHostActivity)context).showFragment(bookDetailFragment);
            }
        });
        return itemView;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((RelativeLayout) object);
    }
}

完成后,管理Fragments的方法:

public void showFragment(final Fragment fragment) {
        if (fragment == null){
            return;
        }

        // Update current fragment.
        //String mFragment = fragment.getClass().getSimpleName();
        // Begin a fragment transaction.
        final FragmentManager fm = getSupportFragmentManager();
        final FragmentTransaction ft = fm.beginTransaction();
        // We can also animate the changing of fragment.
        ft.setCustomAnimations(R.anim.fragment_enter, R.anim.fragment_exit, R.anim.fragment_enter_back, R.anim.fragment_exit_back);
        // Replace current fragment by the new one.
        ft.replace(R.id.fragment_frame_layout, fragment);
        // Null on the back stack to return on the previous fragment when user press on back button.
        ft.addToBackStack(null);
        // Commit changes.
        ft.commit();
    }

0 个答案:

没有答案