Katherina
Katherina

Reputation: 379

Start new Activity with onClick() in RecyclerView

I want to go into a new Activity with the onClick() method but my code is not working. Can you please offer some advice. I have some issues with the recyclerView, since it's fairly new for me. Thank you

public class FragmentOne extends Fragment {

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                    R.layout.recycleview, container, false);
            ContentAdapter adapter = new ContentAdapter();
            recyclerView.setAdapter(adapter);

            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return recyclerView;
        }

        public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
            private static final int LENGTH = 50;

            public ContentAdapter() {
            }

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

                public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                    super(inflater.inflate(R.layout.fragment_channel, parent, false));
                }

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ChannelDetailActivity.class);
                    startActivity(intent);
                }
            }

            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                ViewHolder viewHolder = new ViewHolder (LayoutInflater.from(parent.getContext()), parent);
                return viewHolder;

            }

            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
            }

            @Override
            public int getItemCount() {
                return LENGTH;
            }
        }

    }

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    android:scrollbars="vertical"
    android:elevation="5dp"
    android:fadingEdgeLength="@dimen/cardview_compat_inset_shadow"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<?xml version="1.0" encoding="utf-8"?>



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="360dp"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:layout_marginBottom="1dp"
    android:elevation="2dp"
    android:layout_gravity="center_horizontal"
    android:background="#FFFF">



    <ImageView
        android:id="@+id/user_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@drawable/userone" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:text="Chuck Reich"
        android:paddingBottom="3dp"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/user_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user_name"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:textColor="#a9a9a9"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Horizon Media Studios"
        android:textAppearance="?attr/textAppearanceListItem"
        android:paddingBottom="2dp"
        android:textSize="14sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3928"
        android:paddingRight="18dp"
        android:id="@+id/textView2"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_alignStart="@+id/user_desc" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3402"
        android:id="@+id/textView3"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_toEndOf="@+id/textView2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="2354"
        android:paddingLeft="20dp"
        android:id="@+id/textView4"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Upvotes: 11

Views: 42608

Answers (10)

Branson Camp
Branson Camp

Reputation: 671

Here is a nice solution for people using Kotlin, based on Naveen Yadav's answer:

val context = v.context
val intent = Intent(context, SecondActivity::class.java)
context.startActivity(intent)

Upvotes: 1

Naveen Kumar Yadav
Naveen Kumar Yadav

Reputation: 151

Just Place these lines of code in onClick(View view)

 view.getContext().startActivity(new 
 Intent(view.getContext(),SecondActivity.class));

Upvotes: 3

Zacktamondo
Zacktamondo

Reputation: 2063

This can be very useful for you to get to other Activities

first the recycler view adapter:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

final private ListItemClickListener mOnClickListener;
String[] mStrings;

public MainMenuRVAdapter(String[] tvStrings, ListItemClickListener listener) {
    mStrings = tvStrings;
    mOnClickListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.customRow, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.bind(position);
}

@Override
public int getItemCount() {
    return mStrings.length;
}

public interface ListItemClickListener {
    void onListItemClick(int clickedItemIndex);
}

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView RowTV;

    public ViewHolder (View itemView) {
        super(itemView);
        RowTV = (TextView) itemView.findViewById(R.id.RowTextView);
        itemView.setOnClickListener(this);
    }

    void bind(int listIndex) {
        RowTV.setText(mListStrings[listIndex]);
    }

    @Override
    public void onClick(View v) {
        int clickedPosition = getAdapterPosition();
        mOnClickListener.onListItemClick(clickedPosition);
    }
}
}

Then the MainActivity:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, MainMenuRVAdapter.ListItemClickListener {


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

    String[] stringsArray = getResources().getStringArray(R.array.mainStrings);

    RecyclerView rv = (RecyclerView) findViewById(R.id.RV);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    rv.setLayoutManager(layoutManager);
      rv.setAdapter(new MainMenuRVAdapter(stringsArray, this));
}
  @Override
public void onListItemClick(int clickedItemIndex) {
Intent mIntent;
switch (clickedItemIndex) {
 case 0: //first item in Recycler view
            mIntent = new Intent (MainActivity.this, x.class);
            startActivity(mIntent);
            break;
case 1: //second item in Recycler view
            mIntent = new Intent (MainActivity.this, y.class);
            startActivity(mIntent);
            break;
case 2: //third item in Recycler view
            mIntent = new Intent (MainActivity.this, z.class);
            startActivity(mIntent);
            break;
}

you can use this method and add as many cases to the switch().

Hope I Helped.

Upvotes: 3

Sunil
Sunil

Reputation: 3793

Try this

 public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener    
 {
    public TextView tv_brandName,tv_priceValue;
    ImageView iv_item;
    RelativeLayout rl_share;
    public MyViewHolder(View view) 
    {
        super(view);
        tv_brandName=(TextView)view.findViewById(R.id.tv_brandName);
        tv_priceValue=(TextView)view.findViewById(R.id.tv_priceValue);
        iv_item=(ImageView)view.findViewById(R.id.iv_item);
        rl_share=(RelativeLayout)view.findViewById(R.id.rl_share);
        rl_share.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
             {
              Context context = v.getContext();
                Intent intent = new Intent(context, Share.class);
                context.startActivity(intent);
            }
        });
        context=view.getContext();

    }
 }

}

Upvotes: 0

Katherina
Katherina

Reputation: 379

I found the solution!:) There's this way of handling item click in Recyclerview with itemView given within the ViewHolder class:

 public static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.fragment_channel, parent, false));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, ChannelDetailActivity.class);
                    context.startActivity(intent);
                }
            });
        }
    }

Upvotes: 21

michoprogrammer
michoprogrammer

Reputation: 1199

Try this

public class FragmentOne extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                R.layout.recycleview, container, false);
        ContentAdapter adapter = new ContentAdapter();
        recyclerView.setAdapter(adapter);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return recyclerView;
    }

    public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> implements View.OnClickListener {
        private static final int LENGTH = 50;

        public ContentAdapter() {
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                super(inflater.inflate(R.layout.fragment_channel, parent, false));
            }
        }

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ChannelDetailActivity.class);
            startActivity(intent);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            ViewHolder viewHolder = new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return LENGTH;
        }
    }
}

The adapter now implements the onclick and not the viewholder.

Upvotes: 1

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

Just change getContext() to v.getContext() like this:

        @Override
        public void onClick(View v) {
           v.getContext().startActivity(new Intent(v.getContext(), ChannelDetailActivity.class));

        }

And make your ViewHolder class an inner class of your ContentAdapter class.

Upvotes: 6

Android Geek
Android Geek

Reputation: 9225

context.startActivity( new Intent(context, DifferentActivity.class););

Check here for full solution: How to open a different activity on recyclerView item onclick

Upvotes: 1

Sreehari
Sreehari

Reputation: 5655

Change your logic to this:

    Context baseContext;
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

                 //initial code
                 baseContext = getActivity();
    }        
    @Override
            public void onClick(View v) {
               Intent intent = new Intent(baseContext, ChannelDetailActivity.class));
               startActivity(intent);

            }

Upvotes: 1

Keyur Lakhani
Keyur Lakhani

Reputation: 4371

you have to create constructor of FragmentOne like this

Activity activity;
FragmentOne(Acticity activity){ 
     this.activity = activity;
}

After that start activity with the reference of that activity like this

activity.startActivity(intent);

Upvotes: 1

Related Questions