2016-09-20 54 views
-1

如何将AlertDialog - multipleChoiceItems中的项存储在一个变量中。还有一个分隔符,。我需要它以传递到远程服务器并使用php - explode函数将其解压缩。AlertDialog多项存储在一个变量中带有分隔符

这里是我的演示代码:MainActivity.java

final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl); 
    Button btn = (Button) findViewById(R.id.btn); 
    final TextView tv = (TextView) findViewById(R.id.tv); 

    btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // Build an AlertDialog 
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 

      // String array for alert dialog multi choice items 
      String[] colors = new String[]{ 
        "Red", 
        "Green", 
        "Blue", 
        "Purple", 
        "Olive" 
      }; 

      // Boolean array for initial selected items 
      final boolean[] checkedColors = new boolean[]{ 
        false, // Red 
        true, // Green 
        false, // Blue 
        true, // Purple 
        false // Olive 

      }; 

      // Convert the color array to list 
      final List<String> colorsList = Arrays.asList(colors);` 

builder.setMultiChoiceItems(colors, checkedColors, new DialogInterface.OnMultiChoiceClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which, boolean isChecked) { 

        // Update the current focused item's checked status 
        checkedColors[which] = isChecked; 

        // Get the current focused item 
        String currentItem = colorsList.get(which); 

        // Notify the current action 
        Toast.makeText(getApplicationContext(), 
          currentItem + " " + isChecked, Toast.LENGTH_SHORT).show(); 
       } 
      }); 

我要选择的项目存储在currentItem变量。

因此,样本输出会是这样(在Logcat):Red,Green,Blue,Purple

+0

嗨@RoCk,请接受我的答案,如果它已经为你工作。 –

+0

你好@RoCk,你有答案吗? –

回答

1

你可以在你setMultiChoiceItems onClick事件使用:

currentItem = currentItem+colorsList.get(which)+","; 

Toast.makeText(context,"Appended String :  
"+currentItem,Toast.LENGTH_LONG).show(); 

,并声明你的变量:

String currentItem=""; globally 

发送到服务器时,只需执行以下操作:

currentItem=currentItem.substring(0,currentItem.length()-1); 

它会在最后删除一个额外的“,”。

编辑:

对于在您的按钮onClick事件评论你的问题使用:

for(int i=0;i<colors.length;i++) 
    currentItem = currentItem+colors[i]+","; 

    Toast.makeText(context,"Appended String : "+currentItem,Toast.LENGTH_LONG).show(); 
+1

嘿RoCk试试这个,并让我知道如有任何问题 –

+0

如果我提供了一个按钮来选择它们,我该怎么做? – RoCk

相关问题