Android 存string数组
时间: 2023-08-27 22:04:02 浏览: 53
在 Android 中,你可以在 strings.xml 文件中定义一个 string-array 元素来存储一个字符串数组。以下是一个示例:
在 strings.xml 文件中添加以下代码:
```xml
<string-array name="colors">
<item>Red</item>
<item>Green</item>
<item>Blue</item>
</string-array>
```
然后在代码中,你可以通过以下方式获取该数组:
```java
String[] colors = getResources().getStringArray(R.array.colors);
```
其中,R.array.colors 是在 R.java 文件中自动生成的一个整数常量,它引用了定义在 strings.xml 文件中的字符串数组。通过 getResources() 方法获取到 Resources 实例,然后调用 getStringArray() 方法即可获取该数组。
相关问题
Android getSharedPreferences 存string数组
在 Android 中,你可以使用 SharedPreferences 存储一个字符串数组。下面是一个示例:
```java
// 获取 SharedPreferences 实例
SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
// 创建一个字符串数组
String[] colors = {"Red", "Green", "Blue"};
// 将字符串数组转换为以逗号分隔的字符串
String colorsString = TextUtils.join(",", colors);
// 将字符串数组存储到 SharedPreferences 中
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("colors", colorsString);
editor.apply();
```
在上面的代码中,我们首先获取了一个 SharedPreferences 实例,并将其命名为 "my_prefs"。然后,我们创建了一个字符串数组 colors,将其转换为以逗号分隔的字符串 colorsString,并将其存储到 SharedPreferences 中。在存储时,我们使用了 SharedPreferences.Editor 的 putString() 方法,并将键名设置为 "colors"。
要获取存储的字符串数组,可以使用以下代码:
```java
// 获取 SharedPreferences 实例
SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
// 从 SharedPreferences 中获取存储的字符串数组
String colorsString = sharedPreferences.getString("colors", "");
String[] colors = colorsString.split(",");
// 打印字符串数组
for (String color : colors) {
Log.d("TAG", color);
}
```
在上面的代码中,我们首先获取了一个 SharedPreferences 实例,并将其命名为 "my_prefs"。然后,我们从 SharedPreferences 中获取存储的字符串数组,使用了 SharedPreferences 的 getString() 方法,并将键名设置为 "colors"。获取到字符串数组后,我们使用 String 的 split() 方法将其拆分为一个字符串数组 colors,并打印出每个元素。
android从string数组中删除与textview中相同的元素
你可以按照以下步骤来实现:
1. 获取TextView中的文本内容。
2. 遍历String数组,判断是否存在与TextView中相同的元素。
3. 如果存在相同元素,就将该元素从数组中删除。
4. 更新TextView中的文本内容。
以下是一个示例代码:
```java
String[] stringArray = {"apple", "banana", "orange"};
TextView textView = findViewById(R.id.textView);
String textViewContent = textView.getText().toString();
for (int i = 0; i < stringArray.length; i++) {
if (textViewContent.contains(stringArray[i])) {
List<String> tempList = new ArrayList<>(Arrays.asList(stringArray));
tempList.remove(i);
stringArray = tempList.toArray(new String[0]);
}
}
String updatedTextViewContent = Arrays.toString(stringArray);
textView.setText(updatedTextViewContent);
```
注意:这段代码仅作为示例,实际应用时需要根据具体情况进行修改和优化。