我的设计有一个string.xml文件,其中包含多个包含不同类别的短语。所以我有一个与所有类别有关的活动。如何根据用户对类别的选择来拉特定的数组。假设用户选择一个类别为“常用短语”的常用短语。因此,我将用户选择从一个片段传递到另一个片段,并且正在一个片段上接收该选择,该片段从string.xml文件中提取资源并在列表视图中显示该数组。问题是如何拉特定的数组。假设用户选择是“常用短语” 我使用
接收片段中的字符串String categories = getArguments().getString("categories");
但是为了获得资源,我需要R.array.common,如何将字符串嵌入R.array中。我看不到该怎么做。我不认为打开应用程序时从string.xml文件中提取所有数组是一个好的设计原则,因此我决定在用户选择特定数组时提取特定数组。最后,如果我需要向该数组添加元素,该怎么办。是否可以在运行时更新string.xml文件中的字符串数组?
public class CustomFragment extends Fragment {
private ArrayAdapter<String> adapter;
private ListView listView;
private FloatingActionButton addPhraseButton;
private TextView phraseTitleTextView;
private TextToSpeech textToSpeech;
private String[] phrases;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_custom, container, false);
//receive intent
String categories = getArguments().getString("categories");
Log.v("CATEGO", categories);
Resources res = view.getResources();
final String phrases[] = res.getStringArray(R.array.common);
phraseTitleTextView = view.findViewById(R.id.label_phrases_txtview);
addPhraseButton = view.findViewById(R.id.add_phrases_btn);
// setting local for text to speech
textToSpeech = new TextToSpeech(getActivity().getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
textToSpeech.setLanguage(Locale.US);
}
});
//setting adapter and listview
adapter = new ArrayAdapter<String>(getContext(), R.layout.entry_item, R.id.phrase_textview,phrases);
listView = (ListView) view.findViewById(R.id.phrases_list);
listView.setAdapter(adapter);
listView.setItemsCanFocus(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
String text = phrases[position];
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,null, null);
}
});
return view;
}
}