片段中的RecyclerView通过活动获取位置

时间:2017-03-09 16:47:55

标签: android android-fragments android-recyclerview android-adapter restore

所以这是我的问题,我只有一个活动来自我启动我的viewpager片段,在我的viewpager中我有4个包含recyclerViews的片段。每个片段包含由网络上的数据填充的项目,当我点击一个我得到一个WebView片段,但是当我点击后退按钮时我失去了我的poisiton,导致它重新创建整个活动。

我不知道如何不重新创建活动并恢复原来的位置,或者重新创建它但不改变项目的位置并重新回到原来的位置。这是我的代码。我应该放在哪里?!一些帮助非常好。 谢谢!!

我的活动类:

public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{

    public static final String VIEWPAGER_FRAGMENT = "view_pager";
    private ImageView mImageView;

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

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
        mImageView = (ImageView) findViewById(R.id.logoImageView);

        mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));

        if(!isNetworkAvailable()){

            alertUserAboutError();

        } else {
            relativeLayout.postDelayed(new Runnable() {
                @Override
                public void run() {

                    ViewPagerFragment savedFragment = (ViewPagerFragment)
                            getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);

                    if(savedFragment == null) {
                        ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
                        FragmentManager fragmentManager = getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
                        fragmentTransaction.addToBackStack(null);
                        fragmentTransaction.commit();
                    }
                }
            }, 2000);
        }
    }

    @Override
    public void onListNewSelected(int index, ArrayList<Articles> articles) {
        WebViewFragment webViewFragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
        bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
        webViewFragment.setArguments(bundle);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvailable = true;
        }
        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
        alertDialogFragment.show(getFragmentManager(), "error_dialog");
    }

}

我的ViewPagerClass:

public class ViewPagerFragment extends Fragment {

    public static final String KEY_NEW_INDEX = "key_new_index";
    private ViewPager mViewPager;
    private TabLayout mTabLayout;

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

        final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);

        final OldFactFragment oldFactFragment = new OldFactFragment();

        final SportFragment sportFragment = new SportFragment();

        final BuzzFragment buzzFragment = new BuzzFragment();

        final NewsFragment newsFragment = new NewsFragment();

        mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
        mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
        mViewPager.setOffscreenPageLimit(4);


        mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                if(position == 0){
                    return oldFactFragment;
                } else if (position == 1) {
                    return newsFragment;
                } else if (position == 2){
                    return sportFragment;
                } else return buzzFragment;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                if(position == 0){
                    return "Pastly";
                } else if (position == 1) {
                    return "politic";
                } else if (position == 2){
                    return "sport";
                } else return "buzz";
            }

            @Override
            public int getCount() {
                return 4;
            }

        });

        mTabLayout.setupWithViewPager(mViewPager);

        return view;
    }
}

我的ListFragment(ViewPager中4个片段的父类):

public abstract class ListFragment extends Fragment {

    public static final String KEY_LIST = "key_list";

    public interface OnNewSelectedInterface {
        void onListNewSelected(int index, ArrayList<Articles> articles);
    }

    protected static final String TAG = ListFragment.class.getSimpleName();
    protected ArrayList<Articles> mArticlesList;
    protected ItemAdapter mArticleAdapter;
    protected RecyclerView mRecyclerView;
    protected OnNewSelectedInterface mListener;
    protected RecyclerView.LayoutManager mManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mListener = (OnNewSelectedInterface) getActivity();
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        getInfos(getUrl());
        return view;
    }

    protected abstract String[] getUrl();

    private void getInfos(String[] url) {

        if (isNetworkAvailable()) {

            OkHttpClient client = new OkHttpClient();
            for (int i = 0; i < getUrl().length; i++) {
                Request request = new Request.Builder().url(url[i]).build();

                client.newCall(request).enqueue(new Callback() {

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        try {
                            String jsonData = response.body().string();
                            if (response.isSuccessful()) {
                                Log.v(TAG, jsonData);

                                getMultipleUrls(jsonData);

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        getCurrentArticles(mArticlesList);
                                    }
                                });
                            } else {
                                alertUserAboutError();
                            }
                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                alertUserAboutError();
                            }
                        });
                    }
                });
            }
        } else{
            alertUserAboutError();
        }

    }

    private void getMultipleUrls(String jsonData) throws JSONException {
        if (mArticlesList == null) {
            mArticlesList = getArticleForecast(jsonData);
        } else {
            mArticlesList.addAll(getArticleForecast(jsonData));
        }
    }

    private void getCurrentArticles(ArrayList<Articles> articles) {

        mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);

        mRecyclerView.setAdapter(mArticleAdapter);
        mManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mManager);

    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) getActivity().
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvailable = true;
        }
        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
        alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
    }

    private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        JSONArray articles = forecast.getJSONArray("articles");

        ArrayList<Articles> listArticles = new ArrayList<>(articles.length());

        for (int i = 0; i < articles.length(); i++) {
            JSONObject jsonArticle = articles.getJSONObject(i);
            Articles article = new Articles();

            String urlImage = jsonArticle.getString("urlToImage");

            article.setTitle(jsonArticle.getString("title"));
            article.setDescription(jsonArticle.getString("description"));
            article.setImageView(urlImage);
            article.setArticleUrl(jsonArticle.getString("url"));

            listArticles.add(i, article);
        }

        return listArticles;
    }
}

我的ItemAdapter(适配器类):

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {

    private final ListFragment.OnNewSelectedInterface mListener;
    protected ArrayList<Articles> mArticlesList;
    protected Context mContext;
    private int mPosition;
    private int lastPosition = -1;


    public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
        mContext = contexts;
        mArticlesList = mArticleLi;
        mListener = listener;
    }

    @Override
    public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_linear, parent, false);

        view.findViewById(R.id.textView).setSelected(true);
        ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
        articleViewHolder.setIsRecyclable(false);

        return articleViewHolder;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(ArticleViewHolder holder, int position) {
        mPosition = position;
        holder.bindArticle(mArticlesList.get(position));
        setAnimation(holder.itemView, position);
        holder.mImageView.setClipToOutline(true);


    }

    private void setAnimation(View viewToAnimate, int position) {
        if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }

    @Override
    public int getItemCount() {
        return mArticlesList.size();
    }

    public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{

        private TextView mTitle, mArticle;
        private ImageView mImageView;

        private ArticleViewHolder(View itemView) {
            super(itemView);

            mTitle = (TextView) itemView.findViewById(R.id.textView);
            mArticle = (TextView) itemView.findViewById(R.id.showTextView);
            mImageView = (ImageView) itemView.findViewById(R.id.imageView2);

            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
        }

        private void bindArticle(Articles article) {

            mTitle.setText(article.getTitle());
            mArticle.setText(article.getDescription());
            mArticle.setVisibility(View.INVISIBLE);
            Glide.with(mContext).load(article.getImageView()).into(mImageView);
        }


        @Override
        public void onClick(View view) {
            mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
        }

        @Override
        public boolean onLongClick(View view) {

            String desc = mArticlesList.get(getAdapterPosition()).getDescription();
            mArticle.setVisibility(View.VISIBLE);
            mArticle.setText(desc);
            mArticle.postDelayed(new Runnable() {
                public void run() {
                    mArticle.setVisibility(View.INVISIBLE);
                }
            }, 3000);
            return true;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

在您的方法中onListNewSelected您正在使用旧行片段替换片段

fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);

来自Google Documentaion

  

替换添加到容器的现有片段。这与使用相同的containerViewId添加的所有当前添加的片段调用remove(Fragment),然后使用此处给出的相同参数添加(int,Fragment,String)基本相同。

所以你要移除旧的 Fragment 然后添加新的片段当你回来获取旧的片段时,它还没有从那里创建它将从刮擦,所以已经删除了片段的位置。

在使用add方法时,将新的片段添加到上一个片段上面,当您返回已经存在状态为“位置”的前一个片段