2016-09-20 33 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

相關問題