Transition to a specific activation



  • There's an adapter that uses for a few. recyclerView different fragments.

    In each of the lists, I'm pressuring on the elements that I'm being pushed into.

    final Context context = ((View)personViewHolder.personPhoto.getParent()).getContext();
        ((View)personViewHolder.personPhoto.getParent()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                switch (position) {
                    case 0:
                        intent = new Intent(context, MainActivity.class);
                        break;
                    case 1:
                        intent = new Intent(context, SecondActivity.class);
                        break;
                    default:
                        intent = new Intent(context, ThirdActivity.class);
                        break;
                }
                context.startActivity(intent);
            }
        });
    

    It'd be all right, but since I'm using this adapter for a few fragments, I'm not really good with this option, so I'm always put on the 1st element on the list. MainActivity for all the fragments.

    Again, problem: I cannot move to specific activity/fragments for each list in different fragments.

    I found more. https://stackoverflow.com/a/7894060/6387618 but I don't know how to put it down and what it's like, maybe someone's gonna think, because I'm still on "you."

    Full Adapter code:

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

    public static class PersonViewHolder extends RecyclerView.ViewHolder {

    TextView personName;
    TextView personAge;
    ImageView personPhoto;
    
    PersonViewHolder(View itemView) {
        super(itemView);
        personName = (TextView)itemView.findViewById(R.id.person_name);
        personAge = (TextView)itemView.findViewById(R.id.person_age);
        personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
    }
    

    }

    List<Person> persons;

    public RVAdapter(List<Person> persons){
    this.persons = persons;
    }

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

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

    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, final int position) {
    personViewHolder.personName.setText(persons.get(position).name);
    personViewHolder.personAge.setText(persons.get(position).description);
    personViewHolder.personPhoto.setImageResource(persons.get(position).photoId);

    final Context context = ((View)personViewHolder.personPhoto.getParent()).getContext();
    ((View)personViewHolder.personPhoto.getParent()).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent;
            switch (position) {
                case 0:
                    intent = new Intent(context, MainActivity.class);
                    break;
                case 1:
                    intent = new Intent(context, TestActivity.class);
                    break;
                default:
                    intent = new Intent(context, TestActivity.class);
                    break;
            }
            context.startActivity(intent);
        }
    });
    

    }

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

    One of my fragments code. initializeAdapter)

    public class SecondFragment extends Fragment {

    List<Person> persons;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    initializeData();
    initializeAdapter();
    return view;
    }

    private void initializeData() {
    persons = new ArrayList<>();
    persons.add(new Person("test", "test", R.drawable.profile));
    persons.add(new Person("test", "test", R.drawable.profile));
    persons.add(new Person("test", "test", R.drawable.profile));
    persons.add(new Person("test", "test", R.drawable.profile));
    persons.add(new Person("test", "test", R.drawable.profile));
    persons.add(new Person("test", "test", R.drawable.profile));
    }

    private void initializeAdapter() {
    RVAdapter adapter = new RVAdapter(persons);
    recyclerView.setAdapter(adapter);
    }



  • RecyclerView Not only does it involve initializing the adapter, but also classes. ViewHolder, you may use them and determine which activities should be opened according to the class representing the visual, such as:

        /**
         * Выбирает нужный тип визуалки
         *
         * @param position - позиция элемента
         * @return int - тип визуалки
         */
        @Override
        public int getItemViewType(int position) {
            //в данном случае элементы списка отличаются классом, можно определять и по другим параметрам объекта, как вам удобнее
            Object item = mItems.get(position);
            if (item instanceof Message) {
                return 0;
            } else if (item instanceof TalkItems.TalkDate) {
                return 1;
            }
            return -1;
        }
    
    /**
     * Выбирает нужную визуалку по её типу
     *
     * @param parent   - родительская визуалка
     * @param viewType - тип визуалки
     * @return ViewHolder|null визуалка
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(TalkActivity.this);
        switch (viewType) {
            case 0:
                return new MessageView(
                        inflater.inflate(R.layout.talk_message_my, parent, false)
                );
            case 1:
                return new DateView(
                        inflater.inflate(R.layout.talk_date, parent, false)
                );
            default:
                if (BuildConfig.DEBUG) {
                    throw new AssertionError("Неизвестный тип визуалки");
                }
                return null;
        }
    }
    
    private class MessageView extends RecyclerView.ViewHolder {
    
        MessageView(View itemView) {
            super(itemView);
            final Context context = getApplicationContext();
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(new Intent(context, MainActivity.class));
                }
            });
        }
    }
    
    private class DateView extends RecyclerView.ViewHolder {
    
        DateView(View itemView) {
            super(itemView);
            final Context context = getApplicationContext();
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(new Intent(context, ThirdActivity.class));
                }
            });
        }
    }
    

    If your elements of the list have the same visual, but different content, you can use the following method:

    /**
    * В данном примере используем один класс MessageView, новый класс ниже
    * Заполнение визуальной составляющей элемента
    *
    * @param holder - пустая визуалка
    * @param position - позиция элемента
    */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder == null) {
    return;
    }
    Object item = mItems.get(position);
    final Context context = getApplicationContext();
    MessageView mesHolder = (MessageView) holder;
    if (item instanceof Message) {
    mesHolder.view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    context.startActivity(new Intent(context, MainActivity.class));
    }
    });
    } else if (item instanceof DateItem) {
    mesHolder.view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    context.startActivity(new Intent(context, ThirdActivity.class));
    }
    });
    }
    }

    private class MessageView extends RecyclerView.ViewHolder {
        public View view;
    
        MessageView(View itemView) {
            super(itemView);
            view = itemView;
        }
    }
    




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2