Home » Android » Recycle View on click to open up URL

Recycle View on click to open up URL

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a recycler view that dynamically generates the elements in the view based on my list. However i do not know how to dynamically assign my url to the website image such that when the user clicks on the website image in my UI, it will open up a new browser with the URL assigned to it.

For example if the user clicks on the 1st card R.drawable.website image, it will open “my web URL1”. If he clicks on the 2nd card R.drawable.website image, it will open “my web URL2”.

I would like to use intent in my main activity but all the examples I have seen specifies the website URL specifically meaning i can only specify 1 url. I was wondering if this can be done in the RVAdapter class instead.

RVAdapter.java

import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ImageView;


import com.example.utsav.edufind.R;
import java.util.List;

import entity.PolytechnicCourse;
import entity.UniversityCourse;
import entity.Course;

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.CourseViewHolder> {

    public static class CourseViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView CourseName;
        TextView SchoolName;
        TextView CourseGrade;
        TextView CourseIntake;
        ImageView CourseWebsite;
        ImageView SchoolLogo;
        TextView gradeTitle;

        CourseViewHolder(View itemView) {
            super(itemView);
            cv = itemView.findViewById(R.id.cv);
            CourseName = itemView.findViewById(R.id.Course_name);
            CourseGrade= itemView.findViewById(R.id.Course_Grade);
            SchoolName = itemView.findViewById(R.id.School_name);
            CourseIntake = itemView.findViewById(R.id.Course_Intake);
            CourseWebsite = itemView.findViewById(R.id.Course_Website);
            SchoolLogo = itemView.findViewById(R.id.School_Logo);
            gradeTitle = itemView.findViewById(R.id.Course_Grade_Title);

        }
    }

    List<Course> courses;

    public RVAdapter(List<Course> courses){
        this.courses = courses;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public CourseViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
        CourseViewHolder pvh = new CourseViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(CourseViewHolder CourseViewHolder, int i) {
        if(courses.get(i) instanceof PolytechnicCourse) {
            switch (courses.get(i).getSchool()) {

                case "Singapore Polytechnic": {
                    CourseViewHolder.SchoolLogo.setImageResource(R.mipmap.sp);
                    break;
                }

                case "Ngee Ann Polytechnic": {
                    CourseViewHolder.SchoolLogo.setImageResource(R.mipmap.np);
                    break;
                }

                case "Republic Polytechnic": {
                    CourseViewHolder.SchoolLogo.setImageResource(R.mipmap.rp);
                    break;
                }

                case "Nanyang Polytechnic": {
                    CourseViewHolder.SchoolLogo.setImageResource(R.mipmap.nyp);
                    break;
                }

                case "Temasek Polytechnic": {
                    CourseViewHolder.SchoolLogo.setImageResource(R.mipmap.tp);
                    break;
                }

                default:
            }
            CourseViewHolder.SchoolName.setText(courses.get(i).getSchool());
            CourseViewHolder.CourseName.setText(courses.get(i).getCourseName());
            CourseViewHolder.CourseGrade.setText(String.valueOf(((PolytechnicCourse) courses.get(i)).getL1R4()));
            CourseViewHolder.CourseIntake.setText(String.valueOf(courses.get(i).getIntake()));
            CourseViewHolder.CourseWebsite.setImageResource(R.drawable.website);

            // I want to retrieve the url from String.valueOf(courses.get(i).getWebsite());
            // and put them into a clickable image url (R.drawable.website)
            // In my main UI, when i click on the website logo, it will open up the url in a browser
            CourseViewHolder.CourseWebsite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Problem 1 (variable i is not accessible within inner class)
                    //Problem 2 (startActivity cannot be resolved)
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(courses.get(i).getWebsite())));
                    startActivity(browserIntent);
                }
            });
            CourseViewHolder.gradeTitle.setText("L1R4");
        }

This is what i put in my list in the main page

SearchResultsUI.java

 private void initializeData(){
        courseList = new ArrayList<>();

        courseList.add(new PolytechnicCourse("Diploma in Business Management", "Nanyang Polytechnic",25, 13, "my web URL1"));
        courseList.add(new PolytechnicCourse("Diploma in Digital Media", "Singapore Polytechnic", 400, 11, "my web URL2"));
        courseList.add(new PolytechnicCourse("Diploma in Accountancy", "Singapore Polytechnic", 6700, 19, "my web URL3"));
        courseList.add(new PolytechnicCourse("Diploma in Biological Sciences", "Temasek Polytechnic", 300, 12, "my web URL4"));
    }

This is my XML file

items.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cv"
    android:layout_marginBottom="20dp"
    android:elevation="3dp"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:background="@drawable/relative_background_with_shadow"
        >


        <ImageView
            android:id="@+id/School_Logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:contentDescription="School Logo"/>

        <TextView
            android:id="@+id/Course_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@+id/School_Logo"
            android:layout_marginTop="15dp"
            android:textSize="16sp"
            android:textColor="@color/colorAccent"/>

        <TextView
            android:id="@+id/School_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Course_name"
            android:layout_toEndOf="@+id/School_Logo"
            android:textSize="13sp"
            android:textColor="@color/gray"/>

        <View
            android:id="@+id/view"
            style="@style/Divider"
            android:layout_below="@+id/School_Logo"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/view"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:background="@drawable/linear_background_with_shadow"
            android:gravity="center">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:layout_marginEnd="40dp">
                <ImageView
                    android:id="@+id/Course_Grade_Circle"
                    android:layout_width="65dp"
                    android:layout_height="65dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="3dp"
                    android:background="@drawable/greencircle"/>
                <TextView
                    android:id="@+id/Course_Grade"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:width="80dp"
                    android:textSize="22sp"
                    android:textAlignment="center"
                    android:textStyle="bold"
                    android:textColor="@color/white"
                    android:paddingStart="9dp"
                    android:paddingEnd="20dp"/>
                <TextView
                    android:id="@+id/Course_Grade_Title"
                    android:layout_width="60dp"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/Course_Grade_Circle"
                    android:textSize="16sp"
                    android:layout_marginTop="7dp"
                    android:text="@string/L1R4"
                    android:textAlignment="center"
                    android:layout_marginStart="4dp"/>
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center">
                <ImageView
                    android:id="@+id/Course_Intake_Circle"
                    android:layout_width="65dp"
                    android:layout_height="65dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/greencircle"/>
                <TextView
                    android:id="@+id/Course_Intake"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="28dp"
                    android:minWidth="80dp"
                    android:maxWidth="200dp"
                    android:layout_marginStart="0dp"
                    android:textSize="22sp"
                    android:textAlignment="center"
                    android:textStyle="bold"
                    android:textColor="@color/white"/>
                <TextView
                    android:id="@+id/Course_Intake_Title"
                    android:layout_width="60dp"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/Course_Intake_Circle"
                    android:textSize="16sp"
                    android:layout_marginTop="7dp"
                    android:text="@string/intake"
                    android:textAlignment="center"
                    android:layout_marginStart="8dp"/>
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginStart="40dp">
                <ImageView
                    android:id="@+id/Course_Website"
                    android:layout_width="65dp"
                    android:layout_height="65dp"
                    android:layout_marginTop="10dp"
                    android:contentDescription="Course Website Icon"/>
                <TextView
                    android:id="@+id/Course_Website_Title"
                    android:layout_width="60dp"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/Course_Website"
                    android:textSize="16sp"
                    android:text="@string/website"
                    android:layout_marginTop="7dp"
                    android:textAlignment="center"
                    android:layout_marginStart="6dp"/>
            </RelativeLayout>
        </LinearLayout>
    </RelativeLayout>
</android.support.v7.widget.CardView>
Answers:
   CourseViewHolder.CourseWebsite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("<add url here>"));
            mContext.startActivity(browserIntent);
        }
    });

Get the url from the object and add it.

If you do not know how to pass context follow these steps

In the activity when create adapter object pass context as second parameter

RVAdapter rvAdapter = new RVAdapter(CourseList,this);

In the recycle view class get the context

Context mContext;
public RVAdapter(List<Course> courses,Context context){
    this.courses = courses;
    mContext  = context
}

Questions:
Answers:

First you need to add setOnClickListener function to the ImageView.

CourseViewHolder.CourseWebsite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

Next, you need to modify your RVAdapter constructor so that it will have context property. Context will be used to startActivity.

List<Course> courses;

// Add this property
Context context

// Modify constructor
public RVAdapter(Context context, List<Course> courses){
    this.context = context
    this.courses = courses;
}

Next, inside the setOnClickListener

@Override
public void onClick(View v) {
    final String website = this.courses.get(i).getWebsite()
    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(website));
    this.context.startActivity(browserIntent);            
}