Как обновить точки между CardViews в RecyclerView

Я работаю над приложением-викториной, в котором есть один вопрос и пять переключателей для каждого CardView в RecyclerView. Каждая радиокнопка имеет присвоенный балл.

Например, есть два CardViews

Карточка #1

  • радио_кнопка_1 = -20
  • радио_кнопка_2 = -10
  • радио_кнопка_3 = 0
  • радио_кнопка_4 = 10
  • радио_кнопка_5 = 20

Карточка #2

  • радио_кнопка_1 = -20
  • радио_кнопка_2 = -10
  • радио_кнопка_3 = 0
  • радио_кнопка_4 = 10
  • радио_кнопка_5 = 20

Скажем, пользователь выбирает radio_button_1 в CardView #1, выбирает radio_button_3 в CardView #2 и так далее. Я хочу добавить точки между CardViews и иметь возможность сохранять/сохранять эти точки, когда пользователь прокручивает CardViews. Я не знаю, как это работает с RecyclerView. Общие настройки?

Я добавил текстовое представление, чтобы проверить, обновляется ли оценка в фоновом режиме с новой оценкой.

Адаптер ресайклера:

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
    private List<App> mApps;
    public static int score;

    public static int updateScore() {
        return score;
    }

    public MainAdapter(List<App> apps) {
        mApps = apps;
    }

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

    @Override
    public int getItemViewType(int position) {
        return (position);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        App app = mApps.get(position);
        holder.questionTextView.setText(app.getQuestion());


    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView questionTextView;
        private TextView titleTextView;
        public RadioGroup radioGroup;
        public RadioButton rb1, rb2, rb3, rb4, rb5;

        public ViewHolder(View itemView) {
            super(itemView);
            radioGroup = itemView.findViewById(R.id.radio_group);
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    int selectedValue = 0;
                    switch (checkedId) {
                        case R.id.radio_button_1:
                            selectedValue -= 20;
                            break;
                        case R.id.radio_button_2:
                            selectedValue -= 10;
                            break;
                        case R.id.radio_button_3:
                            selectedValue += 0;
                            break;
                        case R.id.radio_button_4:
                            selectedValue += 10;
                            break;
                        case R.id.radio_button_5:
                            selectedValue += 20;
                            break;
                    }
                    updateValue (selectedValue);

                }

                public int updateValue(int selectedValue) {

                    /**Only to test if value is being tallied**/
                    TextView valueView = titleTextView.findViewById(R.id.title);
                    valueView.setText(String.valueOf(selectedValue));
                    return selectedValue;
                }
            });

            questionTextView = itemView.findViewById(R.id.question);
            titleTextView = itemView.findViewById(R.id.title);

            rb1 = itemView.findViewById(R.id.radio_button_1);
            rb2 = itemView.findViewById(R.id.radio_button_2);
            rb3 = itemView.findViewById(R.id.radio_button_3);
            rb4 = itemView.findViewById(R.id.radio_button_4);
            rb5 = itemView.findViewById(R.id.radio_button_5);
        }

        @Override
        public void onClick(View v) {

            Log.d("App", mApps.get(getAdapterPosition()).getQuestion());
        }
    }}

Основная деятельность:

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;

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

        mRecyclerView = findViewById(R.id.recycler_view);
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mRecyclerView);

        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        setupMainAdapter();
    }

    private void setupMainAdapter() {
        List<App> apps = getApps();
        MainAdapter adapter = new MainAdapter(apps);
        mRecyclerView.setAdapter(adapter);
    }


    private List<App> getApps() {
        List<App> apps = new ArrayList<>();
        apps.add(new App((getResources().getString(R.string.question_1))));
        apps.add(new App((getResources().getString(R.string.question_2))));
        apps.add(new App((getResources().getString(R.string.question_3))));
        apps.add(new App((getResources().getString(R.string.question_4))));
        apps.add(new App((getResources().getString(R.string.question_5))));
        apps.add(new App((getResources().getString(R.string.question_6))));
        apps.add(new App((getResources().getString(R.string.question_7))));
        apps.add(new App((getResources().getString(R.string.question_8))));
        apps.add(new App((getResources().getString(R.string.question_9))));
        apps.add(new App((getResources().getString(R.string.question_10))));

        return apps;
    }
}

XML-карта представления

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="275dp"
    android:layout_height="575dp"
    android:layout_margin="16dp"
    card_view:cardBackgroundColor="@color/colorAccent"
    card_view:cardCornerRadius="0dp"
    card_view:cardElevation="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:fontFamily="@font/futura_medium"
            android:padding="24dp"
            android:textColor="#000000"
            android:textSize="32sp"
            tools:text="@string/title" />

        <TextView
            android:id="@+id/question"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:layout_centerHorizontal="true"
            android:fontFamily="@font/futura_medium"
            android:textColor="#000000"
            android:textSize="18sp"
            tools:text="@string/question" />

        <RadioGroup
            android:id="@+id/radio_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/question"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_margin="16dp"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/radio_button_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:buttonTint="@color/colorPrimaryDark"
                android:text="-2"
                android:textColor="#000000" />

            <RadioButton
                android:id="@+id/radio_button_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:buttonTint="@color/colorPrimaryDark"
                android:text="-1"
                android:textColor="#000000" />

            <RadioButton
                android:id="@+id/radio_button_3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:buttonTint="@color/colorPrimaryDark"
                android:text="0"
                android:textColor="#000000" />

            <RadioButton
                android:id="@+id/radio_button_4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:buttonTint="@color/colorPrimaryDark"
                android:text="1"
                android:textColor="#000000" />

            <RadioButton
                android:id="@+id/radio_button_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:buttonTint="@color/colorPrimaryDark"
                android:text="2"
                android:textColor="#000000" />
        </RadioGroup>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/submit_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_margin="16dp"
            android:layout_marginBottom="32dp"
            android:fontFamily="@font/futura_medium"
            android:text="@string/submit"
            android:textColor="@color/colorAccent"
            android:textSize="16sp"
            app:backgroundTint="@color/colorPrimaryDark"
            app:rippleColor="@color/colorPrimary" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>

person drak    schedule 28.03.2019    source источник
comment
Все, что вы хотите сделать, это переместить updateValue(int) в свою деятельность и спросить, как это сделать? потому что неясно, что ваш вопрос.   -  person ronginat    schedule 28.03.2019
comment
Я обновил свой вопрос, чтобы сделать его более понятным.   -  person drak    schedule 29.03.2019


Ответы (1)


Вы можете объявить interface внутри MainAdapter, назовем его ScoreUpdatesListener. У него есть один метод, который будет вызываться всякий раз, когда вы захотите обновить textView.

Вам нужно будет реализовать этот интерфейс в вашем MainActivity, вы можете сделать это анонимно или сделать так, чтобы этот интерфейс реализовывался самим классом. как class MainActivity implements MainAdapter.ScoreUpdatesListener {}.

В любом случае вам нужно передать эту реализацию интерфейса адаптеру и сохранить его ссылку. Вы можете сделать это в конструкторе или добавить метод set в адаптер.

Теперь при обновлении значения viewHolder вызовите этот слушатель, и он обновит textView из действия.

class MainAdaptaer {
    private ScoreUpdates listener;
    ...

    class ViewHolder... {
        ...

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int selectedValue = 0;
                switch (checkedId) {
                    case R.id.radio_button_1:
                        selectedValue -= 20;
                        break;
                    case R.id.radio_button_2:
                        selectedValue -= 10;
                        break;
                    case R.id.radio_button_3:
                        selectedValue += 0;
                        break;
                    case R.id.radio_button_4:
                        selectedValue += 10;
                        break;
                    case R.id.radio_button_5:
                        selectedValue += 20;
                        break;
                }
                score += selectedValue; 
                // score is an existing attribute of MainAdapter
                // it can and should be non static attribute
                listener.updateScore(score);
            }
    }

    interface ScoreUpdatesListener {
        void onScoreUpdate(int score);
    }
}

В вашей деятельности:

private void setupMainAdapter() {
    List<App> apps = getApps();
    MainAdapter adapter = new MainAdapter(apps, new MainAdapter.ScoreUpdatesListener() {
    @Override
    public void onScoreUpdate(int score) {
        TextView valueView = titleTextView.findViewById(R.id.title);
        valueView.setText(String.valueOf(score));
    }

});
    mRecyclerView.setAdapter(adapter);
}

Если класс сам реализовал интерфейс, просто передайте this адаптеру.

Вам не нужно перемещать обработку TextView в действие, но вы должны это сделать. Адаптер не должен связываться с представлениями, отличными от ViewHolders.

person ronginat    schedule 29.03.2019