如何在android中的字符串数组中传递字符串资源引用

时间:2016-07-15 05:15:34

标签: android arrays

我想在字符串数组中传递字符串资源值,但它没有在数组中取值。它将采用空值

以下是我的代码:

prepaid = getResources().getString(R.string.lbl_prepaid);
dth = getResources().getString(R.string.lbl_dth);

public String[] addedRTHomeList(){
        String[] homeList = {prepaid,dth,"PostPaid","Utility Services","Complaint Entry","Complaint Status","Recharge Status",chat,"Topup Request","Redeem Discount","Private Bus Booking","ST Bus Booking","Hotel Booking","Flight Booking","Money Transfer","Settings","Reports","DTH Activation"};
        return homeList;
    }


for(int i = 0; i < ba.addedRTHomeList().length ; i++)
        {
            md = new MenuDetail();
            md.setMenuName(ba.addedRTHomeList()[i]);
            md.setImageId(ba.RTDrwableListThemeRed()[i]);

            RTmenuListRed.add(md);

            RTMenuThemeRed.put(ba.RTMenuCode()[i],RTmenuListRed);
        }

在for循环中,当我访问addedRTHomeList数组的第一个值时,它取空值

3 个答案:

答案 0 :(得分:0)

您可以在<string-array>中创建string.xml,而不是此。等,

<string-array name="your_array_name">
    <item>Element 1</item>
    <item>Element 2</item>
    <item>Element 3</item>
    <item>Element 4</item>
    .
    .
    .

</string-array>

之后你可以用Java作为,

String[] mTestArray = = getResources().getStringArray(R.array.your_array_name); 

这可能有助于解决您的问题。

答案 1 :(得分:0)

使用AarryList而不是简单数组因为arraylist具有简单的动态实现。

当你创建阵列时,你告诉他它的长度。

public String[] addedRTHomeList(){
        String[] homeList = {prepaid,dth,"PostPaid","Utility Services","Complaint Entry","Complaint Status","Recharge Status",chat,"Topup Request","Redeem Discount","Private Bus Booking","ST Bus Booking","Hotel Booking","Flight Booking","Money Transfer","Settings","Reports","DTH Activation"};
        return homeList;
    }

喜欢上面的homeList是17的大小你不能在18索引中添加值,因为18不存在你为什么会收到此错误

<强>解决方案:

使用String ArrayList示例用法

ArrayList<String> homeList = new ArrayList<String>();

homeList.add("PostPaid");
homeList.add("Complaint Status");
homeList.add("Recharge Status");

.
.
}

从ArrayList homeList.get(index)获取Value。

现在如果添加值,它将创建新索引并在最后添加它。 最好的运气。

答案 2 :(得分:0)

您将获得异常,因为您尝试将变量初始化为类变量。我在addedRTHomeList()方法中移动了初始化,没有发现任何问题。

试试这段代码,

public String[] addedRTHomeList(){
    String prepaid = getResources().getString(R.string.lbl_prepaid);
    String dth = getResources().getString(R.string.lbl_dth);
    String chat = getResources().getString(R.string.lbl_chat);

    return new String[]{prepaid,dth,"PostPaid","Utility Services","Complaint Entry","Complaint Status","Recharge Status",chat,"Topup Request","Redeem Discount","Private Bus Booking","ST Bus Booking","Hotel Booking","Flight Booking","Money Transfer","Settings","Reports","DTH Activation"};
}

String[] items = ba.addedRTHomeList();
for(int i = 0; i < items.length ; i++){
    md = new MenuDetail();
    md.setMenuName(items[i]);
    md.setImageId(ba.RTDrwableListThemeRed()[i]);

    RTmenuListRed.add(md);

    RTMenuThemeRed.put(ba.RTMenuCode()[i],RTmenuListRed);
}