开发者社区> 问答> 正文

如何从arrays.xml文件中获取字符串数组

我只是想显示我的数组中的列表arrays.xml。当我尝试在模拟器中运行它时,我收到了强制关闭消息。

如果我在Java文件中定义数组

String[] testArray = new String[] {"one","two","three","etc"}; 它有效,但是当我使用

String[] testArray = getResources().getStringArray(R.array.testArray); 它不起作用。

这是我的Java文件:

package com.xtensivearts.episode.seven;

import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity { String[] testArray = getResources().getStringArray(R.array.testArray);

/** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Create an ArrayAdapter that will contain all list items ArrayAdapter adapter;

/* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter ( this, android.R.layout.simple_list_item_1, testArray);

// Assign the adapter to this ListActivity setListAdapter(adapter); }

} 这是我的arrays.xml档案

first second third fourth fifth 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 10:31:25 525 0
1 条回答
写回答
取消 提交回答
  • 您无法以testArray这种方式初始化字段,因为应用程序资源仍未准备好。

    只需将代码更改为:

    package com.xtensivearts.episode.seven;

    import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter;

    public class Episode7 extends ListActivity { String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;
    
        mTestArray = getResources().getStringArray(R.array.testArray);    
    
        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);
    
        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
    

    }

    2020-02-08 10:31:39
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关课程

更多

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载