web-dev-qa-db-fra.com

Commencer une nouvelle activité avec onClick () dans RecyclerView

Je veux entrer dans une nouvelle activité avec la méthode onClick () mais mon code ne fonctionne pas. Pouvez-vous s'il vous plaît offrir quelques conseils. J'ai quelques problèmes avec recyclerView, car il est relativement nouveau pour moi. Je vous remercie

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>

6
Katherina

J'ai trouvé la solution! :) Il existe un moyen de gérer les objets en cliquant sur Recyclerview avec itemView dans la classe ViewHolder:

 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);
                }
            });
        }
    }

13
Katherina

Remplacez simplement getContext() par v.getContext() comme ceci:

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

        }

Et faites de votre ViewHolder class une classe interne de votre ContentAdapter class.

5

Il suffit de placer ces lignes de code dans onClick (View View)

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

Vérifiez ici la solution complète: Comment ouvrir une activité différente sur recyclerView item onclick

1
Android Geek

vous devez créer constructeur de FragmentOne comme ceci 

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

Après cela commencer l'activité avec la référence de cette activité comme ceci

activity.startActivity (intention);

1
Keyur Lakhani

Essaye ça

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;
        }
    }
}

L'adaptateur implémente maintenant onclick et non le détenteur de la vue.

1
michoprogrammer

Changez votre logique en ceci:

    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);

            }
1
Sreehari

Voici une solution intéressante pour les utilisateurs de Kotlin, basée sur la réponse de Naveen Yadav:

val context = v.context
val intent = Intent(context, SecondActivity::class.Java)
context.startActivity(intent)
0
Branson Camp

Essaye ça

 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();

    }
 }

}

0
Sunil

Cela peut être très utile pour vous rendre à d’autres activités.

d'abord l'adaptateur de vue recycleur:

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);
    }
}
}

Puis le 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;
}

vous pouvez utiliser cette méthode et ajouter autant de cas au commutateur (). 

J'espère que j'ai aidé.

0
Zacktamondo