如何根据RecyclerView中的单击项在新活动中打开特定片段

时间:2019-02-18 19:58:32

标签: java android android-recyclerview android-viewpager fragment

我有一个带有10条文章的RecyclerView。当我单击RecyclerView(MainActivity)中的项目时,我希望它在新Activity(NewsSingle)中的Fragment中打开。我在新活动中有10个片段(NewsSingleFragment),每个片段代表第一个活动中的文章之一。但是,当我单击第三个RecyclerView项时,它将始终在“片段”中打开第一个项。

MainActivity.java

public class MainActivity extends AppCompatActivity implements 
OnItemClickListener{

private RecyclerView recycler;
private RecyclerAdapter adapter;
private ArrayList<NewsCell> newsList;
private ArrayList<Article> articleList;
private Call<NewsCell> apiCall;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    newsList=new ArrayList<>();
    setupRecycler();
    setUpApiCall();


}

private void popUp(){
    AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
    builder1.setTitle("Greška");
    builder1.setMessage("Ups, dogodila se pogreška.");
    builder1.setCancelable(true);
    builder1.setNeutralButton(android.R.string.ok,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

    AlertDialog alert11 = builder1.create();
    alert11.show();
}

private void setUpApiCall() {
    apiCall = 
NetworkUtils.getApiInterface().getNews("6946d0c07a1c4555a4186bfcade76398", 
"top", "bbc-news");
    apiCall.enqueue(new Callback<NewsCell>() {
        @Override
        public void onResponse(Call<NewsCell> call, Response<NewsCell> 
response) {
            articleList=new ArrayList<Article>();
            articleList.addAll(response.body().getArticles());
            adapter=new 
RecyclerAdapter(MainActivity.this,articleList,MainActivity.this);
            recycler.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<NewsCell> call, Throwable t) {
            Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG);
            popUp();
        }
    });
}


private void setupRecycler() {
    recycler=findViewById(R.id.recyclerView);
    recycler.setLayoutManager(new LinearLayoutManager(this));
}

@Override
public void onItemClick(int position) {
    Intent detailIntent=new Intent(this,NewsSingle.class);

    detailIntent.putParcelableArrayListExtra("articleList",articleList);
    detailIntent.putExtra("int",position);

    startActivity(detailIntent);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (apiCall != null)
        apiCall.cancel();
}

}

NewsSingle.java

public class NewsSingle extends AppCompatActivity {


private ViewPager viewPager;

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

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


}

private void setupPager() {
    PagerAdapter pagerAdapter= new 
ScreenSlidePagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(pagerAdapter);

}

private void initViews() {
    viewPager=findViewById(R.id.viewPager);
}
  }

NewsSingleFragment.java

public class NewsSingleFragment extends Fragment {

private TextView title;
private TextView description;
private ImageView imageView;
private ArrayList<Article> articleList=new ArrayList<Article>();



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

// TODO: Rename and change types and number of parameters
public static NewsSingleFragment newInstance(int i) {
    NewsSingleFragment fragment = new NewsSingleFragment();
    Bundle args = new Bundle();
    args.putInt("position",i);
    fragment.setArguments(args);
    return fragment;
}

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

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle 
savedInstanceState) {

    title=view.findViewById(R.id.tvDetailedTitle);
    description=view.findViewById(R.id.tvDetailedDescription);
    imageView=view.findViewById(R.id.ivDetailImage);
    putText();
}

private void putText() {
    Bundle bundle =getArguments();
    Intent i=getActivity().getIntent();
    int posision= bundle.getInt("position");
    articleList = i.getParcelableArrayListExtra("articleList");
    title.setText(articleList.get(posision).getTitle());
    description.setText(articleList.get(posision).getDescription());

    Picasso.with(getContext()).load(articleList.get(posision)
    .getUrlToImage()).fit().centerInside().into(imageView);
}

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

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_news_single, container, 
false);
}

}

NewsViewHolder.java

public class NewsViewHolder extends RecyclerView.ViewHolder implements 
View.OnClickListener {

public ImageView mIvImage;
public TextView mTvTitle;
public TextView mTvDescription;
private OnItemClickListener itemClickListener;


public NewsViewHolder(@NonNull View itemView,OnItemClickListener listener) 
{
    super(itemView);
    mIvImage=itemView.findViewById(R.id.ivImage);
    mTvTitle=itemView.findViewById(R.id.tvTitle);
    mTvDescription=itemView.findViewById(R.id.tvDescription);
    itemClickListener=listener;
    itemView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    itemClickListener.onItemClick(getAdapterPosition());
}
}

RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<NewsViewHolder> {


private Context mContext;
private List<Article> articleList;
private OnItemClickListener itemClickListener;

public RecyclerAdapter(Context context, ArrayList<Article>  
dataList,OnItemClickListener listener){
    mContext=context;
    articleList=dataList;
    itemClickListener=listener;
}

@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int 
i) {
    View v=
LayoutInflater.from(mContext).inflate(R.layout.cell_news,viewGroup,false);
    return new NewsViewHolder(v, itemClickListener);
}

@Override
public void onBindViewHolder(@NonNull NewsViewHolder newsViewHolder, int i) 
 {
    final Article currentCell=articleList.get(i);

    newsViewHolder.mTvTitle.setText(currentCell.getTitle());
    newsViewHolder.mTvDescription.setText(currentCell.getDescription());
    Picasso.with(mContext).load(currentCell.getUrlToImage())
    .fit().centerInside().into(newsViewHolder.mIvImage);

    }


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

ScreenSlidePagerAdapter.java

public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

private static final int NUM_PAGES=10;


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

@Override
public Fragment getItem(int position) {
    switch(position){
        case 0:
            return NewsSingleFragment.newInstance(0);
        case 1:
            return NewsSingleFragment.newInstance(1);
        case 2:
            return NewsSingleFragment.newInstance(2);
        case 3:
            return NewsSingleFragment.newInstance(3);
        case 4:
            return NewsSingleFragment.newInstance(4);
        case 5:
            return NewsSingleFragment.newInstance(5);
        case 6:
            return NewsSingleFragment.newInstance(6);
        case 7:
            return NewsSingleFragment.newInstance(7);
        case 8:
            return NewsSingleFragment.newInstance(8);
        case 9:
            return NewsSingleFragment.newInstance(9);
        default:
            return NewsSingleFragment.newInstance(0);
    }
}

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

我希望在Recycler中单击第五篇文章时,在Fragment中打开第五篇文章。

1 个答案:

答案 0 :(得分:0)

我通过添加setCurrentItem(position);来修复它;进入新活动。 所以代码是这样的。

Intent i=getIntent();
int position= i.getIntExtra("int",0);
viewPager.setCurrentItem(position);

毕竟很简单的解决方案...