使用Android切换按钮/开关的选定状态



我想在我当前的应用程序中添加一个切换按钮或开关。我想做的是将当前点击的状态写入一个字符串,以便稍后由应用程序的另一部分调用。

我最终要做的是使用微调器中的选定项,然后使用开关的状态将两者结合起来,并将其写入文本文件或Db。

因此,微调器工作并写入,我可以将其选定的状态保存如下。

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SelectedServer = parent.getItemAtPosition(position).toString();
}

因此,当我稍后在代码中保存这些数据时,我可以调用SelectedServer字符串来保存这些数据。

我的问题是,我如何为交换机复制这一点,其中一个状态将为true,并保存值&true,另一个表示false并保存值&false稍后调用。

原因是,保存的值稍后将添加到微调器中选定的项目中。

所有帮助,建议感谢

Dave

****存储设置事件

public void saveSettings(View view) {
File txtFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder/");
if (!txtFolder.exists()) {
txtFolder.mkdir();
}
File file = new File(txtFolder, "setting.txt");
String.valueOf(SelectedServer.getBytes());
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(SelectedServer.getBytes());
fos.close();
Toast.makeText(getApplicationContext(),"Setting Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

所以我想做的是我有的地方

FileOutputStream fos = new FileOutputStream(file);
fos.write(SelectedServer.getBytes());

我将添加切换开关的状态,所以我正在查看类似fos.write(SelectedServer+SelectedState.getBytes())的内容;

但这似乎不起作用,有没有办法像这样将这些字符串连接到保存的字符串中?

在Android开发者库中有一个切换开关的好例子。(https://developer.android.com/guide/topics/ui/controls/togglebutton.html)

设置setOnCheckedChangeListener将允许您更改字符串。

String toggleisChecked;
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//Set the string to true
toggleIsChecked = "true";
} else {
// Set the string to false
toggleIsChecked = "false";
}
}

});

从你的问题中,我不太确定你是否也在问如何将两个值组合到同一个字符串中,所以最快的解释是在你的资源中创建一个字符串,例如:

<string name="current_states">%1$s &amp; %2$s</string>

然后,当设置该字符串时,您将添加两个值,如下所示:

String whateverYouWantToShow;
whateverYouWantToShow = getString(R.string.current_states, SelectedServer, toggleIsChecked);

这会将值放入字符串资源中。

希望这能有所帮助!

最新更新