如何实现共享preferences在Android的单选按钮如何实现、单选、按钮、Android

2023-09-04 05:43:06 作者:向你心口开枪

我是一个福利局到Android,请耐心等待。

I'm a newb to Android, so please be patient.

我试图建立一个新的应用程序,它需要是这样的:

I'm trying to set up a new app and it needs to look like this:

每个类别都有多种选择。每个选项都有两个字符串来表示该选项的名称和它的配置信息。用户选择通过点击单选按钮的选项。应该有两个无线电组:一个用于每个类别。图像不显示它,但应该有保存和取消按钮在屏幕的底部。

Each category has a number of options. Each option has two Strings to denote the option's name and its configuration information. The user selects an option by tapping on the radio button. There should be two radio groups: one for each category. The image doesn't show it, but there should be "save" and "cancel" buttons at the bottom of the screen.

有关的布局,我为了显示键和值(这只是TextViews)呼吁GETALL。这是我迷路了。

For the layout, I called getAll in order to display the key and value (which are just TextViews). This is where I'm lost.

在我不知道如何与一个单选按钮链接preference。 在我不知道该如何保存更改(因为我不知道如何连接preference一个单选按钮)。 我也想实现像一个脏位来表示是否真的保存之前的变化,但我不知道这是Android最好的做法是。

正如你所看到的,我完全失去了。因此,任何帮助将是非常,大大AP preciated。

As you can see, I'm completely lost. So, any help would be really, greatly appreciated.

推荐答案

我假设你创建自己的活动与自己的布局。在这种情况下,您将无法访问自动化preference装载和的 preferenceActivity 。

I assume you're creating your own Activity with your own layout. In this case you won't have access to the automated preference loading and saving mechanisms provided by PreferenceActivity.

您必须取消一切手工:在OnCreate(),你应该添加事件侦听器来取消和保存按钮:

You will have to de everything by hand: in the onCreate() you should add an event listener to Cancel and Save buttons:

Button saveButton = (Button)findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      save();
   }
});

在save()方法,你必须从单选按钮要求选择状态,并保存您的选择在共享preferences:

In the save() method you have to request selection state from the radio buttons, and store your selections in the shared preferences:

private void save() {
   String prefValue = (RadioButton)findViewById(R.id.firstButton).isChecked()?"First string":"Second string";
   SharedPreferences pref = PreferencesManager.getDefaultSharedPreference(this);
   pref.edit().putString("PrefName", prefValue).commit();
}

有关的脏位,有两种解决方法:添加一个点击监听器单选按钮,如果其中任何一个点击,你说脏。或者,您可以添加这些听众,并要求当前选择,并决定如果是从初始状态不同。

For the "dirty bit", there are two solutions: you add a click listener to the radio buttons, and if any of them is clicked, you say dirty. Or you can add those listeners, and request the current selections, and decide if it is different from the initial state.

另一种方法是创建一个preferencesActivity,以preferences.xml在那里你可以指定键和值来存储选定的项目。

The other way would be to create a PreferencesActivity, with a preferences.xml where you can specify which keys and values to store for a selected item.

 
精彩推荐
图片推荐