微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何从arraylist中的strings.xml调用字符串

我使用的是ArrayList,并且所有字符串都在适配器中进行了硬编码,但现在我需要为我的应用程序提供多语言支持.我认为最好的方法是将我所有的硬编码字符串移动到strings.xml文件中,然后生成我需要的所有不同语言的字符串文件.

我已经将硬编码字符串移动到我的strings.xml但我现在不确定如何在Arraylist中调用它们而不是在那里使用硬编码字符串.

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

List<AdapterData> mItems;

public Adapter() {
super();
mItems = new ArrayList<>();
AdapterData data = new AdapterData();
data.setQuestion("How Old Are You?");
data.setAnswer("I Am 21 Years Old");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Where Were You Born?");
data.setAnswer("I Was Born In The USA");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Are You Male or Female?");
data.setAnswer("I Am Male");
mItems.add(data);



}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
        .inflate(R.layout.recycler_view_card_item, viewGroup, false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
AdapterData data = mItems.get(i);
viewHolder.mName.setText(data.getQuestion());
viewHolder.mNameTwo.setText(data.getAnswer());
 }


@Override
public int getItemCount() {

return mItems.size();
}

class ViewHolder extends RecyclerView.ViewHolder{

public TextView mQuestion;
public TextView mAnswer;


public ViewHolder(View itemView) {
    super(itemView);
    mQuestion = (TextView)itemView.findViewById(R.id.layoutQuestion);
    mAnswer = (TextView)itemView.findViewById(R.id.layoutAnswer);

}
}

}

解决方法:

只是为了提供替代方案,您还可以使用字符串数组

<string name="how_old_are_you">How old are you?</string>
<string name="are_you_male_or_female">Are you male or female?</string>
...

<string name="i_am_21">I am 21 years old</string>
<string name="i_was_born_in_the_usa">I was born in the USA</string>
...

<string-array name="questions">
  <item>@string/how_old_are_you</item>
  <item>@string/are_you_male_or_female</item>
  ...
</string-array>

<string-array name="answers">
  <item>@string/i_am_21</item>
  <item>@string/i_was_born_in_the_usa</item>
  ...
</string-array>

要使用字符串数组作为列表,

List<String> questions = Arrays.asList(getResources().getStringArray(R.array.questions));

它可能会派上用场.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。