2017-02-20 2 views
0

listview에 약간의 문제가 있습니다. 버튼을 클릭 할 때 checkbox가 선택된 listview 값을 가져 오려고합니다. 지금까지 내가 체크 박스 목록보기를 생성하고 mysql에서 모든 값을 가져 왔지만 체크 된 listview 값을 가져올 수 없다. listview 체크 박스에서 값을 얻는 방법?

public class ListViewMultipleSelectionActivity extends Activity{ 
    Button button; 
    String myJSON; 

    private static final String TAG_NAME = "cat_name"; 

    JSONArray peoples = null; 

    ArrayList<HashMap<String, String>> personList; 

    ListView list1; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     personList = new ArrayList<HashMap<String,String>>(); 
     list1 = (ListView) findViewById(R.id.list); 
     button = (Button)findViewById(R.id.testbutton); 
     getlat(); 



     button.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 


      } 
     }); 

    } 

    public void getlat(){ 
     class GetDataJSON extends AsyncTask<String, Void, String> { 
      public void onPreExecute() { 
      } 
      @Override 
      protected String doInBackground(String... params) { 

       InputStream inputStream = null; 
       String result = null; 
       try { 

        URL url = new URL("http://xxxxxxxxxxxx/category.php"); 

        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
        conn.setReadTimeout(15000 /* milliseconds */); 
        conn.setConnectTimeout(15000 /* milliseconds */); 
        conn.setRequestMethod("POST"); 
        conn.setDoInput(true); 
        conn.setDoOutput(true); 
        OutputStream os = conn.getOutputStream(); 

        os.close(); 

        int responseCode=conn.getResponseCode(); 

        if (responseCode == HttpsURLConnection.HTTP_OK) { 

         BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream())); 
         StringBuilder sb = new StringBuilder(""); 
         String line=""; 
         while ((line = in.readLine()) != null) 
         { 
          sb.append(line).append("\n"); 
         } 
         result = sb.toString(); 
        } 

        assert inputStream != null; 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line).append("\n"); 
        } 
        result = sb.toString(); 
       } catch (Exception e) { 
        Log.i("tagconvertstr", "["+result+"]"); 
        System.out.println(e); 
       } 
       finally { 
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
       } 
       return result; 
      } 

      @Override 
      protected void onPostExecute(String result){ 

       myJSON = result; 
       showList(); 

      } 
     } 
     GetDataJSON g = new GetDataJSON(); 
     g.execute(); 
    } 



    protected void showList(){ 
     try { 
      peoples = new JSONArray(myJSON); 
      for(int i=0;i<peoples.length();i++){ 

       JSONObject c = peoples.getJSONObject(i); 
       String name = c.getString(TAG_NAME); 

       HashMap<String,String> persons = new HashMap<String,String>(); 

       persons.put(TAG_NAME,name); 

       personList.add(persons); 
      } 



      ListAdapter adapter = new SimpleAdapter(
        ListViewMultipleSelectionActivity.this, personList, R.layout.result, 
        new String[]{TAG_NAME}, 
        new int[]{R.id.name} 
      ); 




      list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
      list1.setAdapter(adapter); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 



} 

main.xml에 내 클래스입니다

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <Button 
     android:id="@+id/testbutton" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:text="Submit" /> 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_above="@id/testbutton" 
     android:layout_alignParentTop="true"/> 

</RelativeLayout> 

내가 testbutton (버튼)에이를 구현 한

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:orientation="horizontal" > 

<CheckBox 
    android:id="@+id/cbBox" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center_vertical" > 
</CheckBox> 

<LinearLayout 
    android:id="@+id/linearLayout1" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="5dp" 
    android:orientation="vertical" 
    android:layout_weight="1" > 

    <TextView 
     android:id="@+id/name" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:textStyle="bold"/> 

</LinearLayout> 

</LinearLayout> 

result.xml 확인하시기 바랍니다 클릭

button.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       SparseBooleanArray checked = list1.getCheckedItemPositions(); 
       ArrayList<String> selectedItems = new ArrayList<String>(); 
       for (int i = 0; i < checked.size(); i++) { 
        int position = checked.keyAt(i); 
         if (checked.valueAt(i)) 
         selectedItems.add((String) adapter.getItem(position)); 
       } 

       String[] valuess = new String[selectedItems.size()]; 

       for (int i = 0; i < selectedItems.size(); i++) { 
        valuess[i] = selectedItems.get(i); 
       } 
       Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show(); 
      } 
     }); 

이 난의 getView에서 'convertView'(어댑터의) 방법이 될 수있는 당신의 행보기로 클릭 한 후 태그와

E/-->>>>: [Ljava.lang.String;@ca01299 
+2

가능한 중복 http://stackoverflow.com/questions/19027843/android-get-text-of-all-checked-checkboxes-in -listview) –

+0

테스트 버튼의 모든 체크 된 값을 원합니까? –

+0

네, testbutton을 클릭하면, 나는 listview의 모든 값을 확인하고 싶습니다. –

답변

0
  1. 설정 체크 박스 객체를 얻고있다.

  2. 행보기에서 클릭 수신기로 작성하십시오. 3. 클릭 리스너가 onClick 메서드의 매개 변수 인 뷰에서 getTag를 뷰 행으로 가져 와서 해당 체크 박스 객체에 대해 checkbox로 캐스팅 한 다음 setChecked를 true로 설정합니다.

코드는

convertView.setTag(yourCheckBoxObject); 
    convertView.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      CheckBox cb = (CheckBox) v.getTag(); 
      cb.setChecked(true); 
     } 
    }); 

어댑터에 대한 자세한 내용은 Getting an issue while checking the dynamically generated checkbox through list view

0

이 광경을 당신 것 그 방법)의 getView (라고 한 @Override 방법이되었다 참조하십시오, 다음과 같이 보일 수 있습니다 클릭 한 현재 항목을 가져 오십시오.

holder.checkbox.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

    CheckBox checkBox=(CheckBox) view; 
     String tagName=""; 
    if(checkBox.isChecked()){ 
     tagName=checkBox.getTag().toString(); 
     deleteServices.add(tagName); 
     checkboxArrayList.add(checkBox); 
    }else { 
      checkboxArrayList.remove(checkBox); 
      tagName=checkBox.getTag().toString(); 
       if(deleteServices.size()>0&&deleteServices.contains(tagName)){ 

deleteService s.remove (tagName); }을 지원하는 사용자 정의 어댑터와 함께이 값을 저장하는 사용자 정의 클래스를 만드는 당신이 할 수있는

 }); 
1

. 따라서 버튼을 클릭 할 때마다 주어진 함수를 호출하여 해당 항목의 상태를 검색 할 수 있습니다. 아래에 주어진 아키텍처 예 :

추신 : 내가 선택한 값으로 무엇을하고 싶은지 모르겠으므로, 필요에 따라 변경할 수있는 주석을 남겼습니다.

MainActivity.java

package com.rencsaridogan.stackoverflow; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ListView; 
import java.util.ArrayList; 

public class MainActivity extends AppCompatActivity { 

    ArrayList<ExampleClass> objects; 

    @Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    objects = new ArrayList<>(); 

    for (int i = 0; i < 10; i++){ 
     objects.add(new ExampleClass("Example Name " + i)); 
    } 

    final ListView listView = (ListView) findViewById(R.id.listView); 
    final Button testButton = (Button) findViewById(R.id.testButton); 
    final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects); 
    listView.setAdapter(exampleAdapter); 
    exampleAdapter.notifyDataSetChanged(); 

    testButton.setOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 
     getCheckedItems(); 
     } 
    }); 

    } 

    private void getCheckedItems(){ 
    for (int i = 0; i < 10; i++) { 
     if (objects.get(i).isChecked()){ 
     Log.i("MainActivity",i + " is checked"); 
     /** 
     * Value is checked, do what you need to do here 
     */ 
     } else { 
     Log.i("MainActivity",i + " is NOT checked"); 
     /** 
     * Value is NOT checked 
     */ 
     } 
    } 
    } 
} 

ExampleAdapter.java

package com.rencsaridogan.stackoverflow; 

import android.annotation.SuppressLint; 
import android.content.Context; 
import android.support.annotation.NonNull; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.CheckBox; 
import android.widget.CompoundButton; 
import android.widget.TextView; 
import java.util.ArrayList; 
/** 
* Created by rencsaridogan on 16/02/2017. 
*/ 

public class ExampleAdapter extends ArrayAdapter<ExampleClass> { 

    ArrayList<ExampleClass> objects; 
    Listener listener; 
    Context context; 

    public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) { 
    super(context, resource); 
    this.context = context; 
    this.objects = objects; 
    } 

    @Override public int getViewTypeCount() { 
    return super.getViewTypeCount(); 
    } 

    @Override public int getCount() { 
    return objects.size(); 
    } 

    @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { 

    if (convertView == null){ 
     Log.i("ExampleAdapter","ConvertView inflated"); 
     convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false); 
    } 

    Log.i("ExampleAdapter","Setting of values"); 

    final ExampleClass data = objects.get(position); 
    final ViewHolder viewHolder = new ViewHolder(); 

    viewHolder.textView = (TextView) convertView.findViewById(R.id.textView); 
    viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); 

    viewHolder.textView.setText(data.getName()); 

    viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     data.setChecked(isChecked); 
     } 
    }); 

    return convertView; 
    } 

    public void setListener(Listener listener) { 
    this.listener = listener; 
    } 

    private class ViewHolder { 

    TextView textView; 
    CheckBox checkBox; 
    } 

    public ArrayList<ExampleClass> getObjects() { 
    return objects; 
    } 

    public void setObjects(ArrayList<ExampleClass> objects) { 
    this.objects = objects; 
    notifyDataSetChanged(); 
    } 

    @Override public long getItemId(int position) { 
    return super.getItemId(position); 
    } 

    public interface Listener { 
    void onCheckedChanged(int position); 
    } 
} 

하여 ExampleClass.자바

package com.rencsaridogan.stackoverflow; 

/** 
* Created by rencsaridogan on 16/02/2017. 
*/ 

public class ExampleClass { 
    String name; 
    boolean isChecked; 

    public ExampleClass(String name) { 
    this.name = name; 
    } 

    public ExampleClass(String name, boolean isChecked) { 
    this.name = name; 
    this.isChecked = isChecked; 
    } 

    public String getName() { 
    return name; 
    } 

    public void setName(String name) { 
    this.name = name; 
    } 

    public boolean isChecked() { 
    return isChecked; 
    } 

    public void setChecked(boolean checked) { 
    isChecked = checked; 
    } 
} 
[목록보기 안드로이드 모든 텍스트가 선택받을 체크 박스 (의
관련 문제