如何使用资源中的字符串数组声明数组?

时间:2018-02-24 21:23:30

标签: android arrays string android-arrayadapter

我在资源目录中创建了一个包含三个项值的字符串数组。然后尝试将数组放入字符串x中。它没有显示任何错误,但崩溃。

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3

字符串数组代码如下 -

 String x[]= getResources().getStringArray(R.array.z_array);
    String y[]={"1","2","3"};
enter code here

如果我使用

,而不是像上面那样声明x []
<string-array name="z_array">
<item>a</item>
<item>b</item>
<item>c</item>

工作正常。

这是我的自定义适配器代码 -

     String x[]= {"a","b","c"};

我的问题是如何使用资源中的字符串数组声明数组?

Logcat

   public class MyCustomAdapter extends ArrayAdapter{
    public MyCustomAdapter(Context context, int textViewResourceId,
                           String[] objects,String[] objects2){

        super(context, textViewResourceId, objects);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = getLayoutInflater();

        View view = inflater.inflate(R.layout.activity_list_view, parent, false);

        TextView nameV= (TextView) view.findViewById(R.id.uuuu);

        nameV.setText(x[position]);

        TextView authorNameV = (TextView) view.findViewById(R.id.vvvv);
        authorNameV.setText(y[position]);

        switch (position) {
            default:
                break;
        }

        return view ;
    }

}

1 个答案:

答案 0 :(得分:0)

您从资源获取阵列的代码是可以的。为了确保您的x[]值,您可以在logcat

上打印它们
for (String name : x) {
        Log.d(name);
    }

有一个很大但是,我想你在MainActivity中创建了你的适配器作为一个内部类吧?

如果否:您的x []和y []为空。 如果是:告诉我如何实现您的适配器并将其设置为列表视图。