简体   繁体   English

关闭应用程序后如何保存按钮的背景?

[英]How to save the background of a button after closing the app?

I've been working on a social app on android and I have an issue that I couldn't solve. 我一直在使用android上的社交应用程序工作,但是有一个我无法解决的问题。 I have a button in every item of my ListView . 我的ListView每个项目都有一个按钮。

When the user presses this button, the background changes to another color but when I close the app the color of the button should become the default color. 当用户按下此按钮时,背景会更改为另一种颜色,但是当我关闭应用程序时,按钮的颜色应成为默认颜色。

Try this: 尝试这个:

Create a model class for storing the color information of each list item. 创建一个用于存储每个列表项的颜色信息的模型类。

ListModel.java ListModel.java

public class ListModel implements Serializable
{
    String title;
    int color;

    public ListModel(String title, int color) {
        this.title = title;
        this.color = color;
    }

    public String getTitle() {
        return title;
    }

    public int getColor() {
        return color;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setColor(int color) {
        this.color = color;
    }
}

In activity, create initialize the ListView and assign an adapter to it. 在活动中,创建初始化ListView并为其分配适配器。 Here, when user presses the back button, we will convert the list of color information into JSON using GSON library and store it into SharedPreferences . 在这里,当用户按下“后退”按钮时,我们将使用GSON库将颜色信息列表转换为JSON并将其存储到SharedPreferences And when activity is created, get the JSON from the SharedPreferences and again convert it back into List object using GSON . 创建活动后,请从SharedPreferences获取JSON ,然后使用GSON将其再次转换回List对象。

Activity.java Activity.java

public class MainActivity extends AppCompatActivity {

    private MyListAdapter adapter;
    private List<ListModel> dataList;
    private SharedPreferences preferences;

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

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        if (preferences.contains("Key")) {
            String jsonStr = preferences.getString("Key", "");
            Type type = new TypeToken<List<ListModel>>() {
            }.getType();
            dataList = new Gson().fromJson(jsonStr, type);
        } else {
            dataList = new ArrayList<>();
            fillData();
        }

        ListView listView = (ListView) findViewById(R.id.listview);

        adapter = new MyListAdapter(this, dataList);
        listView.setAdapter(adapter);
    }

    public void changeColor(int position) {
        dataList.get(position).setColor(getResources().getColor(R.color.blue));
    }

    private void fillData() {
        int color = getResources().getColor(R.color.black);
        dataList.add(new ListModel("Button 1", color));
        dataList.add(new ListModel("Button 2", color));
        dataList.add(new ListModel("Button 3", color));
        dataList.add(new ListModel("Button 4", color));
        dataList.add(new ListModel("Button 5", color));
        dataList.add(new ListModel("Button 6", color));

        adapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        SharedPreferences.Editor editor = preferences.edit();
        //Set the values
        Gson gson = new Gson();
        String json = gson.toJson(dataList);
        editor.putString("Key", json);
        editor.apply();
    }
}

MyListAdapter.java MyListAdapter.java

public class MyListAdapter extends BaseAdapter
{
    private final Context context;
    private final List<ListModel> list;

    public MyListAdapter(Context context, List<ListModel> list)
    {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }
    /*private view holder class*/
    private class ViewHolder {
        Button button;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.button = (Button) convertView.findViewById(R.id.listItemBtn);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }


        ListModel model = list.get(position);
        holder.button.setText(model.getTitle());
        holder.button.setBackgroundColor(model.getColor());
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.setBackgroundColor(context.getResources().getColor(R.color.blue));
                ((MainActivity)context).changeColor(position);

            }
        });
        return convertView;
    }
}

And in build.gradle , add GSON dependency build.gradle ,添加GSON依赖项

compile 'com.google.code.gson:gson:2.2.4'

Essentially you shouldn't rely on the the buttons themselves, you should have something called model behind the scene to store state of those buttons. 从本质上讲,您不应该依赖按钮本身,而应该在幕后有一个称为模型的东西来存储这些按钮的状态 So, you can save that model, which stores state of all buttons, to a persistent memory (eg Database, file, Shared Preferences, etc) when your app is closed. 因此,您可以在关闭应用程序时将存储所有按钮状态的模型保存到永久内存(例如数据库,文件,共享首选项等)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 关闭后如何将应用程序保留在后台-PhoneGap - How to keep the app in the background after closing - PhoneGap 按下alertDialog上的保存按钮后,Android应用强制关闭 - Android app force closing after press save button on alertDialog 关闭后保存游戏应用 - Save game app after closing 关闭后如何保存我的Android应用程序的状态? - How to save state of my android app after closing? 关闭应用程序后保存用户名和密码 - Save username and password after closing the app 关闭应用程序后,hashmap 中的数据不保存 - Data in hashmap does not save after closing app 关闭应用程序后保持开关按钮的状态 - Keep the state of switch button after closing the app 即使应用程序被强制停止,也要重新启动服务,即使关闭应用程序,也要在后台继续运行服务如何? - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? 即使应用程序被强制停止,也要重新启动服务;关闭应用程序后,仍要在后台运行服务。 - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? 如何防止应用程序在后台关闭? - How to prevent app from closing on background?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM