【问题标题】:Get selected list item in alert dialog with split string使用拆分字符串在警报对话框中获取选定的列表项
【发布时间】:2014-07-24 01:19:18
【问题描述】:

我在 strings.xml 中有字符串数组,其中国家电话号码和国家名称用逗号分隔。 现在我想在对话框中显示此列表,并在编辑文本中显示所选国家/地区的电话号码。

显示列表,我可以单击一个项目,并且在编辑文本中显示一个不带国家名称的数字,但不幸的是它始终是相同的值。看起来我没有得到点击的项目,但遍历了完整的列表并得到了一些东西。

这是警报对话框的代码:

private void selectCountry() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.choose_country);
final String[] names = getResources().getStringArray(R.array.Countries);
builder.setItems(names, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {

        String CountryZipCode = "";

        for (int i = 0; i < names.length; i++) {
            String[] g = names[i].split(",");
            CountryZipCode = g[0];
        }

        countrycode.setText("+" + CountryZipCode);
    }
});

AlertDialog alert = builder.create();
alert.show();
}

这是来自 strings.xml 的数组列表的 sn-p:

<string-array name="Countries" >
    <item>93,Afghanistan</item>
    <item>355,Albania</item>
    <item>213,Algeria</item>
    <item>376,Andorra</item>
    <item>244,Angola</item>
</string-array>

提前非常感谢!

【问题讨论】:

    标签: android listview split android-alertdialog


    【解决方案1】:

    总是最后一个吗?

    因为如果我正确阅读了您的代码,那就是您在做什么..

    你不应该说:

    builder.setItems(names, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
    
            String CountryZipCode = "";
    
            //for (int i = 0; i < names.length; i++) {
                String[] g = names[item].split(",");
                CountryZipCode = g[0];
            //}
    
            countrycode.setText("+" + CountryZipCode);
        }
    });
    

    【讨论】:

    • 你是对的!它总是最后一个!非常感谢您的快速回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多