RecyclerView の項目は Android にそのまま残ります

okwaves2024-01-24  6

下の画像では、ユーザーがrecyclerviewの項目をクリックすると、「単語に追加」と表示されます。

単語に追加

ただし、アプリを閉じて再度開くと、「単語に追加」に戻ります。

単語に追加

ユーザーがアプリを再度開いたときもこれを同じにしたいと考えています。

TodayFragment.java

public class TodayFragment extends Fragment {

    private RecyclerView wordRecyclerView;
    private DbHelper dbHelper;
    private SQLiteDatabase mDatabase;
    private Context mContext;

    WordAdapter mWordAdapter;


    private static final String LOG_TAG = "TodayFragment";

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


        dbHelper = new DbHelper(mContext);
        mDatabase = dbHelper.getWritableDatabase();


    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(LOG_TAG,"onAttach");
        mContext = context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(LOG_TAG,"onDetach");
        mContext = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_today,container,false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        wordRecyclerView = view.findViewById(R.id.word_recycler_view);
       // wordRecyclerView.setHasFixedSize(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);

        wordRecyclerView.setLayoutManager(linearLayoutManager);

        String query = "select * from wordhistory;";
        Cursor c = mDatabase.rawQuery(query, new String[] {});

        Log.d(LOG_TAG,"cursor count, "+c.getCount());

        Log.d(LOG_TAG,"onViewCreated set recycler view");

        mWordAdapter = new WordAdapter(mContext);


        wordRecyclerView.setAdapter(mWordAdapter);

        mWordAdapter.swapCursor(c);
        mWordAdapter.notifyDataSetChanged();



    }
}

fragment_today.xml

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    tools:context=".fragment.TodayFragment">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <androidx.recyclerview.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:id="@+id/word_recycler_view" />


        </LinearLayout>




</androidx.core.widget.NestedScrollView>

WordAdapter.java

public class WordAdapter extends BaseCursorAdapter<WordAdapter.WordViewHolder> {

    private static final String LOG_TAG = "WordAdapter";

    Context mContext;

    private OnItemClickListener mListener;

    private int touchCount=0;
    Cursor mCursor;


    public WordAdapter(Context mContext) {
        super(null);

        this.mContext = mContext;

    }

    public interface OnItemClickListener{
        void onItemClick(int position);

    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }


    @NonNull
    @Override
    public WordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view;
        view = layoutInflater.inflate(R.layout.word_card_layout,parent,false);

        Log.d(LOG_TAG,"onCreateViewHolder: ");

        return new WordViewHolder(view);
    }

    @Override
    public void onBindViewHolder(WordViewHolder holder, Cursor cursor) {

        int wordColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD);
        int defColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_DEFINITION);
        int audioColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_AUDIOURL);
        int synonymColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_SYNONYMS);
        int antonymColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_ANTONYMS);

        String wordStr = cursor.getString(wordColumnIndex);
        String wordDefStr = cursor.getString(defColumnIndex);
        String audioStr = cursor.getString(audioColumnIndex);
        String synonymStr = cursor.getString(synonymColumnIndex);
        String antonymStr = cursor.getString(antonymColumnIndex);

        Log.d(LOG_TAG,"onBindViewHolder wordStr: "+wordStr);
        Log.d(LOG_TAG,"onBindViewHolder wordDefStr: "+wordDefStr);

        holder.wordTextView.setText(wordStr);
        holder.defTextView.setText(wordDefStr);
    }

  /*  @Override
    public int getItemCount() {
        return mCursor.getCount();
    }*/


    @Override
    public void swapCursor(Cursor newCursor) {
        super.swapCursor(newCursor);
    }



    public class WordViewHolder extends RecyclerView.ViewHolder {
        TextView wordTextView;
        ImageView audioImageView;
        TextView defTextView;
        TextView wordTrickTextView;
        TextView defTrickTextView;
        ImageView shareImageView;
        ImageView favUnselectImageView;
        ImageView favSelectImageView;
        TextView addWordTextView;
        TextView addedWordTextView;
        ImageView tickImageView;
        RelativeLayout addWordRelativeLayout;



        public WordViewHolder(@NonNull View itemView) {
            super(itemView);

            Log.d(LOG_TAG,"WordViewHolder itemView: "+itemView);

            wordTextView = itemView.findViewById(R.id.wordText);
            audioImageView = itemView.findViewById(R.id.wordAudio);
            defTextView = itemView.findViewById(R.id.wordDef);
            wordTrickTextView = itemView.findViewById(R.id.memorisingTrickWord);
            defTrickTextView = itemView.findViewById(R.id.memorisingTrickDef);
            shareImageView = itemView.findViewById(R.id.wordShare);
            favUnselectImageView = itemView.findViewById(R.id.wordFavUnselect);
            favSelectImageView = itemView.findViewById(R.id.wordFavSelect);
            addWordTextView = itemView.findViewById(R.id.addWordText);
            addedWordTextView = itemView.findViewById(R.id.addedWordText);
            tickImageView = itemView.findViewById(R.id.tickImage);
            addWordRelativeLayout = itemView.findViewById(R.id.addWordRelativeLayout);

            addedWordTextView.setVisibility(View.GONE);
            tickImageView.setVisibility(View.GONE);


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

                    if (touchCount==0){
                        addWordTextView.setVisibility(View.GONE);
                        addedWordTextView.setVisibility(View.VISIBLE);
                        tickImageView.setVisibility(View.VISIBLE);

                        ((Animatable) tickImageView.getDrawable()).start();
                        touchCount=1;
                    } else{
                        addWordTextView.setVisibility(View.VISIBLE);
                        addedWordTextView.setVisibility(View.GONE);
                        tickImageView.setVisibility(View.GONE);

                        ((Animatable) tickImageView.getDrawable()).stop();
                        touchCount=0;
                    }

                }
            });





        }
    }
}

ユーザーは、アプリを再度開いた後でも、リサイクラー ビューの任意の項目で行った変更を確認できる必要があります。



------------------------

アプリを閉じると、システムはアクティビティを自動的に破棄します。したがって、開いたときにもう一度実行すると、アクティビティが再作成されます。

savedInstanceState を使用すると、アクティビティが破棄される前にアクティビティのデータを保存できます。

アクティビティで onSaveInstanceState メソッドをオーバーライドし、バンドルに追加する必要があります。以下はコード例です。

@Override
public void onSaveInstanceState(Bundle saveInstanceState){
    // example, save if text is added
    saveInstanceState.putBoolean("Herbivore", true); 
    super.onSaveInstanceState(saveInstanceState);
}

アクティビティが開始すると、OnCreate からバンドルを受け取ることができます。

@Override
boolean herbivoreAdded;
public void OnCreate(Bundle onSaveInstanceState){
   super.OnCreate(saveInstanceState);
   // access saved value
   herbivoreAdded = saveInstanceState.getBoolean("Herbivore");
}

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。