我使用的是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));
它可能会派上用场.