2012-03-23 2 views
1

레이아웃 뷰어를 통해 listview에 체크 박스를 넣으려고했지만 성공했으나 여러 연락처를 선택할 때 아무런 문제가 없지만 선택을 취소하면 & 스크롤 할 때 문제가 발생합니다. & 아래 다음 ... 그이 자동으로 선택 얻을 해제 체크 박스로 돌아가여러 연락처 선택 목록의 체크 박스

public class Contactlist_selfActivity extends ListActivity { 
/** Called when the activity is first created. */ 

private ArrayList<contact> contact_list = null; 
private ProgressDialog mProgressDialog = null; 
private contactAdapter mContactAdapter = null; 
private Runnable mViewcontacts = null; 
private SparseBooleanArray mSelectedContacts = new SparseBooleanArray(); 
private ArrayList<contact> items; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    contact_list = new ArrayList<contact>(); 
    this.mContactAdapter = new contactAdapter(this, R.layout.listview, 
      contact_list); 
    ListView lv = getListView(); 
    setListAdapter(this.mContactAdapter); 
    lv.setItemsCanFocus(false); 
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    // } 
    mViewcontacts = new Runnable() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      getContacts(); 
     } 
    }; 

    Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground"); 
    thread.start(); 
    mProgressDialog = ProgressDialog.show(Contactlist_selfActivity.this, 
      "Please Wait...", "Retriving Contacts...", true); 
} 

@SuppressWarnings("unused") 
private void getContacts() { 
    // TODO Auto-generated method stub 

    try { 

     String[] projection = new String[] { 
       ContactsContract.Contacts.DISPLAY_NAME, 
       ContactsContract.Contacts.HAS_PHONE_NUMBER, 
       ContactsContract.Contacts._ID }; 

     Cursor mCursor = managedQuery(
       ContactsContract.Contacts.CONTENT_URI, projection, 
       ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?", 
       new String[] { "1" }, 
       ContactsContract.Contacts.DISPLAY_NAME); 

     while (mCursor.moveToNext()) { 
      contact contact = new contact(); 

      String contactId = mCursor.getString(mCursor 
        .getColumnIndex(ContactsContract.Contacts._ID)); 

      contact.setContactName(mCursor.getString(mCursor 
        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))); 
      contact_list.add(contact); 
     } 
     mCursor.close(); 

     runOnUiThread(returnRes); 

    } catch (Exception e) { 
     // TODO: handle exception 
     Log.d("getContacts", e.getMessage()); 
    } 
} 

public class contactAdapter extends ArrayAdapter<contact> { 
    private int[] isChecked; 

    public contactAdapter(Context context, int textViewResourceId, 
      ArrayList<contact> items1) { 
     super(context, textViewResourceId, items1); 
     items = items1; 
    } 

    @Override 
    public View getView(final int position, View convertView, 
      ViewGroup parent) { 
     // TODO Auto-generated method stub 
     final int position_clicked = 0; 
     // Log.i("asd", "getView :" + getItem(position)); 

     if (convertView == null) { 

      LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = vi.inflate(R.layout.listview, parent, false); 
     } 

     contact contacts = items.get(position); 
     isChecked = new int[items.size()]; 

     if (contacts != null) { 
      final CheckBox nameCheckBox = (CheckBox) convertView 
        .findViewById(R.id.checkBox); 
      nameCheckBox.setChecked(mSelectedContacts.get(position)); 

      for (int i = 0; i < isChecked.length; i++) { 

      } 

      if (nameCheckBox != null) { 
       nameCheckBox.setText(contacts.getContactName()); 
      } 

      nameCheckBox.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        isChecked[position_clicked] = position; 
        Log.d("position", String.valueOf(position)); 
       } 
      }); 

     } 

     return convertView; 
    } 
} 

private Runnable returnRes = new Runnable() { 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     if (mProgressDialog.isShowing()) 
      mProgressDialog.dismiss(); 
     mContactAdapter.notifyDataSetChanged(); 
    } 
}; 
} 

답변

11

에 내가 ... 대답 .... 난 그냥 연락처 클래스에 새로운 변수를 가져 갔다 발견

public class PlanetsActivity extends Activity { 
private ListView mainListView; 
private Contact[] contact_read; 
private Cursor mCursor; 
private ArrayAdapter<Contact> listAdapter; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // Find the ListView resource. 
    mainListView = (ListView) findViewById(R.id.mainListView); 

    mainListView 
      .setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View item, 
         int position, long id) { 
        Contact planet = listAdapter.getItem(position); 
        planet.toggleChecked(); 
        ContactViewHolder viewHolder = (ContactViewHolder) item 
          .getTag(); 
        viewHolder.getCheckBox().setChecked(planet.isChecked()); 
       } 
      }); 

    // Throw Query and fetch the contacts. 

    String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER, 
      Contacts._ID, Contacts.DISPLAY_NAME }; 

    mCursor = managedQuery(Contacts.CONTENT_URI, projection, 
      Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" }, 
      Contacts.DISPLAY_NAME); 

    if (mCursor != null) { 
     mCursor.moveToFirst(); 
     contact_read = new Contact[mCursor.getCount()]; 

     // Add Contacts to the Array 

     int j = 0; 
     do { 

      contact_read[j] = new Contact(mCursor.getString(mCursor 
        .getColumnIndex(Contacts.DISPLAY_NAME))); 
      j++; 
     } while (mCursor.moveToNext()); 

    } else { 
     System.out.println("Cursor is NULL"); 
    } 

    // Add Contact Class to the Arraylist 

    ArrayList<Contact> planetList = new ArrayList<Contact>(); 
    planetList.addAll(Arrays.asList(contact_read)); 

    // Set our custom array adapter as the ListView's adapter. 
    listAdapter = new ContactArrayAdapter(this, planetList); 
    mainListView.setAdapter(listAdapter); 
} 

/** Holds Contact data. */ 
@SuppressWarnings("unused") 
private static class Contact { 
    private String name = ""; 
    private boolean checked = false; 

    public Contact() { 
    } 

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

    public Contact(String name, boolean checked) { 
     this.name = name; 
     this.checked = checked; 
    } 

    public String getName() { 
     return name; 
    } 

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

    public boolean isChecked() { 
     return checked; 
    } 

    public void setChecked(boolean checked) { 
     this.checked = checked; 
    } 

    public String toString() { 
     return name; 
    } 

    public void toggleChecked() { 
     checked = !checked; 
    } 
} 

/** Holds child views for one row. */ 
@SuppressWarnings("unused") 
private static class ContactViewHolder { 
    private CheckBox checkBox; 
    private TextView textView; 

    public ContactViewHolder() { 
    } 

    public ContactViewHolder(TextView textView, CheckBox checkBox) { 
     this.checkBox = checkBox; 
     this.textView = textView; 
    } 

    public CheckBox getCheckBox() { 
     return checkBox; 
    } 

    public void setCheckBox(CheckBox checkBox) { 
     this.checkBox = checkBox; 
    } 

    public TextView getTextView() { 
     return textView; 
    } 

    public void setTextView(TextView textView) { 
     this.textView = textView; 
    } 
} 

/** Custom adapter for displaying an array of Contact objects. */ 
private static class ContactArrayAdapter extends ArrayAdapter<Contact> { 

    private LayoutInflater inflater; 

    public ContactArrayAdapter(Context context, List<Contact> planetList) { 
     super(context, R.layout.simplerow, R.id.rowTextView, planetList); 
     // Cache the LayoutInflate to avoid asking for a new one each time. 
     inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // Contact to display 
     Contact planet = (Contact) this.getItem(position); 
     System.out.println(String.valueOf(position)); 

     // The child views in each row. 
     CheckBox checkBox; 
     TextView textView; 

     // Create a new row view 
     if (convertView == null) { 
      convertView = inflater.inflate(R.layout.simplerow, null); 

      // Find the child views. 
      textView = (TextView) convertView 
        .findViewById(R.id.rowTextView); 
      checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01); 

      // Optimization: Tag the row with it's child views, so we don't 
      // have to 
      // call findViewById() later when we reuse the row. 
      convertView.setTag(new ContactViewHolder(textView, checkBox)); 

      // If CheckBox is toggled, update the Contact it is tagged with. 
      checkBox.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        CheckBox cb = (CheckBox) v; 
        Contact contact = (Contact) cb.getTag(); 
        contact.setChecked(cb.isChecked()); 
       } 
      }); 
     } 
     // Reuse existing row view 
     else { 
      // Because we use a ViewHolder, we avoid having to call 
      // findViewById(). 
      ContactViewHolder viewHolder = (ContactViewHolder) convertView 
        .getTag(); 
      checkBox = viewHolder.getCheckBox(); 
      textView = viewHolder.getTextView(); 
     } 

     // Tag the CheckBox with the Contact it is displaying, so that we 
     // can 
     // access the Contact in onClick() when the CheckBox is toggled. 
     checkBox.setTag(planet); 

     // Display Contact data 
     checkBox.setChecked(planet.isChecked()); 
     textView.setText(planet.getName()); 

     return convertView; 
    } 

} 

public Object onRetainNonConfigurationInstance() { 
    return contact_read; 
} 

}

+0

나는 또한 유사한 문제에 직면하고있다. 프로젝트를 zip 파일에 올리시겠습니까? –

+0

@TapanDesai 이것은 전체 클래스 형제 다. ... 그 밖에 당신이 원하는 .. .. ??? – Wolverine

+0

동일한 코드를 사용해 보았지만 사용 중 일식에서 오류가 발생했습니다 .. 보관함에있는 경우 프로젝트를 게시하십시오 –

2

이것의 원인은 당신이 코드에서 OnClickListener() 각성을 nameCheckBox.setChecked()를 호출하고 해당 코드를 실행할 때. 나는 동일한 문제를 해결하기 전에 체크 박스를 설정하기 전에 OnClickListener(null)을 설정하는 것으로 해결했다.

+0

내가 onClick에서 null을 전달하면 클릭 한 항목을 얻는 방법 ??? ??? & u는 정확하게 할 수있는 더 많은 wht를 정교하게 만들 수 있습니다 .. ??? & thenx .. – Wolverine

+0

setChecked()를 호출하기 전에 onClick()에서 null을 전달해야합니다. 그런 다음 onClick()에서 메서드를 전달해야합니다. – redandblack

+0

코드에 다음과 같이 표시 될 수 있습니다. nameCheckBox.setOnClickListener (null); nameCheckBox.setChecked (mSelectedContacts.get (position)); – redandblack

2

nameCheckBox.setOnClickListener (새 OnClickListener를() {

  @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       isChecked[position_clicked] = position; 
       Log.d("position", String.valueOf(position)); 
      } 
     }); 

이 코드의 저장의 모든 위치를 한 번 더하게 거쳐리스트를 추가하고 추가 또는 제거가 모두 상기 빠르고 추가 번째 제거한다. 하고 나열 할 위치 다른 방법

+0

하지만 아래로 스크롤하면 연락처 선택을 취소했다. 내가 생각했던 wht를 얻었지만 선택이 취소 된 상태로 전환되는 방법이 선택되었습니다. ??? – Wolverine