从AnotherActivity调用片段到MainActivity

时间:2017-09-08 10:25:17

标签: android android-fragments android-activity

我有一个包含RecyclerView项的活动。
AnotherActivity,我有很多片段。单击RecyclerView时,应打开AnotherActivity的片段。
请帮忙!!

这是来自活动的Recycler Adapter 已修改的代码

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final Item item = itemList.get(position);

    holder.name.setText(item.getName());
    // Picasso.with(mContext).load(item.getPic()).into(holder.imageView);

    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        int pos = holder.getAdapterPosition();

        @Override
        public void onClick(View view) {
            //  Toast.makeText(mContext, "Hello" + item.getName(), Toast.LENGTH_SHORT).show();

            switch (pos) {
                case 0:
                    // Toast.makeText(mContext, "zero", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, WebSlider.class);
                    mContext.startActivity(intent);
                    break;
                case 1:
                     //call  particular fragment 
                    ...........
                    }
                }
}

使用viewpager的另一项活动

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

    fm = getSupportFragmentManager();

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

Viewpager适配器......

 public void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

    adapter.addFragment(new Chapter1(), "");
    adapter.addFragment(new Chapter2(), "");
    adapter.addFragment(new Chapter3(), "");
    viewPager.setAdapter(adapter);
}


public class ViewPagerAdapter extends FragmentPagerAdapter {
    ........................
}

1 个答案:

答案 0 :(得分:-1)

试试这个

如果您在其他活动中使用TabLayout而不是关注我的代码

在一个包含Recyclerview

的活动中
Intent i = new Intent(your_context, YourAnotherActivity.class);
i.putBooleanExtra("key", true);
startActivity(i);

在你的otherActivity.java

if (getIntent().getExtras() != null && getIntent().getBooleanExtra("key",false))
{
    viewPager.setCurrentItem(2);//pass viewPagerFragemtnt position 
}