Favourite button Android [closed]

江枫思渺然 提交于 2019-12-03 20:32:01

Use ToggleButton in your XML:

<ToggleButton
    android:layout_width="180dp"
    android:layout_height="180dp"
    android:id="@+id/myToggleButton"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textOn=""
    android:textOff=""/>

And in your Activity:

ToggleButton toggleButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(false);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.img_star_grey));
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.img_star_yellow));
            else
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.img_star_grey));
        }
    });
}

use the code for change Background Button also you can save state button in SharedPreferences

    favouritebtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean isFavourite = readStae();

            if (isFavourite) {
                favouritebtn.setBackgroundResource(R.drawable.imgStarGrey);
                isFavourite = false;
                saveStae(isFavourite);

            } else {
                favouritebtn.setBackgroundResource(R.drawable.imgStaryellow);
                isFavourite = true;
                saveStae(isFavourite);

            }

        }
    });

also add the Method

  private void saveStae(boolean isFavourite) {
    SharedPreferences aSharedPreferenes = this.getSharedPreferences(
            "Favourite", Context.MODE_PRIVATE);
    SharedPreferences.Editor aSharedPreferenesEdit = aSharedPreferenes
            .edit();
    aSharedPreferenesEdit.putBoolean("State", isFavourite);
    aSharedPreferenesEdit.commit();
}

private boolean readStae() {
    SharedPreferences aSharedPreferenes = this.getSharedPreferences(
            "Favourite", Context.MODE_PRIVATE);
    return aSharedPreferenes.getBoolean("State", true);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!