如何在共享首选项中保存按钮状态?

时间:2019-05-24 06:56:22

标签: java android sharedpreferences

我是Android开发的新手,我有自定义ListView,该按钮具有收藏夹和 removefavourite 按钮,现在我想将此按钮状态保存在SharedPreferences中,请告诉我如何当用户单击“收藏夹”按钮时,此按钮状态保存为共享首选项,该按钮变为收藏夹,当单击收藏夹时,该按钮更改为 removefavourite 这是我的代码吗?

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

                ischeckd=true;
                holder.addfavoruite.setVisibility(View.GONE);
                holder.removefavoruite.setVisibility(View.VISIBLE);

        }
    });

    holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
ischeckd=false;
            holder.addfavoruite.setVisibility(View.VISIBLE);
            holder.removefavoruite.setVisibility(View.GONE);

        }
    });

我的自定义ListView完整代码

package bible.swordof.God;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;

import java.util.List;
import java.util.Locale;

import es.dmoral.toasty.Toasty;

import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;

public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;

    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private  boolean ischeckd;
    String My_PREF="MY_PREF";
    SharedPreferences sharedPreferences;


    //check for availabe language
    int result;


    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;



    }


    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder


            holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ImageView)convertView.findViewById(R.id.adbookmark);
            holder.removefavoruite=(ImageView)convertView.findViewById(R.id.removebookmark);


            try {


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

                ischeckd=true;
                holder.addfavoruite.setVisibility(View.GONE);
                holder.removefavoruite.setVisibility(View.VISIBLE);

        }
    });

    holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
ischeckd=false;
            holder.addfavoruite.setVisibility(View.VISIBLE);
            holder.removefavoruite.setVisibility(View.GONE);

        }
    });

}catch (Exception e){

    Toast.makeText(activity, ""+e, Toast.LENGTH_SHORT).show();
}

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));
        holder.verselist.setText(verselist.get(position));


        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);

            }
        });


        textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

                if (status == TextToSpeech.SUCCESS) {
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                } else {

                    Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                }
            }
        });




        //My toggle button





        //mDBHelper = new DatabaseHelper(activity);
        //mDb = mDBHelper.getWritableDatabase();



        //ContentValues contentValues=new ContentValues();
        //contentValues.put("id",verseid.get(position));
        //contentValues.put("bookname",refernce.get(position));
        //contentValues.put("versenumber",versenumber.get(position));
        //contentValues.put("verse",verselist.get(position));
        //long check=mDb.insert("favourite",null,contentValues);





        //Log.d("MY_TAG","DB IS NOW "+check);



        //Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();



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

                Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                    Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                } else {


                    textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);

                }
            }
        });


        /* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

             mDBHelper = new DatabaseHelper(activity);
               mDb = mDBHelper.getWritableDatabase();

              // long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});




               //Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
            }
        });*/


        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;

        private ImageView share;
        private  ImageView addfavoruite;
        private  ImageView removefavoruite;
        private ImageView speakverse;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
            share = (ImageView) v.findViewById(R.id.share);
            speakverse = (ImageView) v.findViewById(R.id.speakverse);
            addfavoruite=(ImageView)v.findViewById(R.id.adbookmark);
            removefavoruite=(ImageView)v.findViewById(R.id.removebookmark);

        }


    }
    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();

        }
        cursor.close();


        return true;
    }

}

2 个答案:

答案 0 :(得分:0)

您只需要创建一个AppPreference类:-

 public class AppPrefrences {

            private static SharedPreferences mPrefs;
            private static SharedPreferences.Editor mPrefsEditor;

            public static boolean isButtonCLicked(Context ctx) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                return mPrefs.getBoolean("button_clicked", true);
            }

            public static void setButtonCLicked(Context ctx, Boolean value) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                mPrefsEditor = mPrefs.edit();
                mPrefsEditor.putBoolean("button_clicked", value);
                mPrefsEditor.commit();
            }

        }

并在您的按钮中单击设置此方法:-

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

                ischeckd=true;
                holder.addfavoruite.setVisibility(View.GONE);
                holder.removefavoruite.setVisibility(View.VISIBLE);

                AppPreference.setButtonCLicked(activity, ture);

        }
    });

并获得如下所示的按钮状态:-

boolean isButtonClicked = AppPreference.isButtonCLicked(activity);

答案 1 :(得分:0)

我有一些建议。首先,建议您将ToggleButton用作自己喜欢的按钮。其次,我建议您使用RecyclerView代替ListView(实际上已弃用)。第三,建议您创建一个数据类(最好使用AutoValue):

class Verse {
    private final int number;
    private final String list;
    private final String ref;
    private final String id;
    private final boolean isFavourite;
    //Constructor and getters...
}

并替换为:

List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid

与此:

List<Verse> verses

关于坚持哪些经节未被选中,那么我建议您偏爱SQLiteDatabase而不是SharedPreferences。但是,如果您使用共享的首选项,则需要一种将诗歌链接到其选中状态的方法。我假设您的id值是唯一的,因此您可以使用它:

class VersePreferences {

    private static final String VERSE_KEY = "com.my.packagename.VERSE_KEY";

    private final SharedPreferences prefs;

    private VersePreferences(SharedPreferences prefs) {
        this.prefs = prefs;
    }

    static VersePreferences from(Context context) {
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
        return new VersePreferences(prefs);
    }

    void save(List<Verse> verses) {
        final Set<String> set = new HashSet<>(verses.size());
        for(Verse verse : verses) {
            final String serialized = String.format("%s:%s", verse.id(), Boolean.toString(verse.isFavourite()));
        }
        prefs.edit().putStringSet(VERSE_KEY, set).apply();
    }

    Map<String, Boolean> load() {
        final Set<String> set = prefs.getStringSet(VERSE_KEY, new HashSet<>());
        final Map<String, Boolean> map = new HashMap<>();
        for(String serialized : set) {
            final String[] parts = serialized.split(":");
            map.put(parts[0], Boolean.parseBoolean(parts[1]);
        }
        return map;
    }

}

通过将地图中的String id值与Boolean值进行比较,可以确定哪个是不受欢迎的经文。

示例用法...

//OnClick
VersePreferences.from(Context).save(verses); //save all verses

//To load
final Map<String, Boolean> checkedStates = VersePreferences.from(context).load();

for(int i = 0; i < verses.size(); i++) {
   final Verse current = verses.get(i);
   final boolean checkedState = checkedState.get(current.id());
   final Verse checked = current.toBuilder().setChecked(checkedState).build(); //Example using builder pattern
   verses.set(i, checked);
}