2013-11-26 5 views
0

У меня есть пользовательский ListView, и я поместил три TextView в список с помощью специального адаптера списка! Как я могу добавить CheckBox с каждым элементом списка и сделать каждый CheckBox установленным на элементе списка?CheckBox в пользовательском ListView на Android

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/name" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:textColor="#7a4b9d" 
     android:textSize="15sp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/calorie" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:text="sdf" 
     android:textColor="#ffffff" /> 

    <TextView 
     android:id="@+id/price" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:text="sdf" 
     android:textColor="#ffffff" /> 
    <CheckBox 
     android:id="@+id/chkBox1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="CheckBox" /> 

</LinearLayout> 

MainActivity

public class Main_Activity extends Fragment implements OnClickListener { 

    private ListView lv; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     ViewGroup root = (ViewGroup) inflater.inflate(R.layout.main_activity, null); 


     ArrayList<SearchResults> searchResults = GetSearchResults(); 

     final ListView lv = (ListView) root.findViewById(R.id.list_two); 
     lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
     lv.setTextFilterEnabled(true); 
     lv.setAdapter(new MyCustomBaseAdapter(getActivity(), searchResults)); 

     lv.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> a, View v, int position, 
        long id) { 

            boolean result = searchResults.get(position).isSolved(); 
       if (result) { 
        searchResults.get(position).setSolved(false); 
       } else { 
        searchResults.get(position).setSolved(true); 
       } 

       Toast.makeText(getActivity(),"You have chosen: " + " " + 
       fullObject.getPhone(), Toast.LENGTH_SHORT).show(); 

      } 
     }); 

     return root; 

    } 

    private ArrayList<SearchResults> GetSearchResults() { 
     ArrayList<SearchResults> results = new ArrayList<SearchResults>(); 

     SearchResults sr = new SearchResults(); 
     sr.setName("Apple"); 
     sr.setCalorie("35"); 
     sr.setPrice("5"); 
     results.add(sr); 

     return results; 
    } 


} 

Пользовательские Базовый адаптер

public class MyCustomBaseAdapter extends BaseAdapter { 
    private static ArrayList<SearchResults> searchArrayList; 

    private LayoutInflater mInflater; 

    public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) { 
     searchArrayList = results; 
     mInflater = LayoutInflater.from(context); 
    } 

    public int getCount() { 
     return searchArrayList.size(); 
    } 

    public Object getItem(int position) { 
     return searchArrayList.get(position); 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.custom_row_view, null); 
      holder = new ViewHolder(); 
      holder.txtName = (TextView) convertView.findViewById(R.id.name); 
      holder.txtCalorie = (TextView) convertView 
        .findViewById(R.id.calorie); 
      holder.txtPrice = (TextView) convertView.findViewById(R.id.price); 
    holder.chkBox1 = (CheckBox)convertView.findViewById(R.id.chkBox1); 


     convertView.setTag(holder); 
    } else { 
     holder = (ViewHolder) convertView.getTag(); 
    } 

    holder.txtName.setText(searchArrayList.get(position).getName()); 
    holder.txtCalorie.setText(searchArrayList.get(position) 
      .getCalorie()); 
    holder.txtPrice.setText(searchArrayList.get(position).getPrice()); 
    holder.chkBox1.setChecked(searchArrayList.get(position).isSolved()); 


    return convertView; 
} 

static class ViewHolder { 
    CheckBox chkBox1; 
    TextView txtName; 
    TextView txtCalorie; 
    TextView txtPrice; 
} 

Результаты поиска

public boolean isSolved() { 
    // TODO Auto-generated method stub 
    return b; 
} 

public void setSolved(boolean b) { 
    // TODO Auto-generated method stub 
    this.b = b; 
} 
+0

И в чем вопрос? – SimonSays

+0

Как я могу добавить CheckBox в пользовательский список? @SimonSays –

ответ

2

Вы должны определить свой вид CheckBox в custom_row_view.xml файле первых,

<CheckBox android:id="@+id/chkBox1" 
android:layout_width=... 
android:layout_height=... /> 

Затем вы WLL должны вызвать эту ссылку в вашем MyCustomBaseAdapter классе или в держателе в вашем случае, как

CheckBox chkBox1; 

затем,

holder.chkBox1 = = (CheckBox)convertView.findViewById(R.id.chkBox1); 

Вы можете определить логическое значение в вашем классе SearchResults, который может позаботиться о проверке и использовании chkBox

holder.chkBox1.setChecked(searchArrayList.get(position).isSolved()); 

Что-то на этих строках, и вам будет хорошо идти :)

EDIT: Не забудьте изменить значение boolean в searchResult экземпляре на itemClick.

boolean result = searchResults.get(position).isSolved(); 
if (result) { 
    searchResults.get(position).setSolved(false); 
} else { 
    searchResults.get(position).setSolved(true); 
} 
lv.getAdapter().notifyDataSetChanged(); 
+0

Вызовите 'adapter.notifyDataSetChanged();' после того, как вы изменили модель searchResults. –

+0

Есть ли какое-либо условие для результата if (...) {} else {}? –

+0

'результат' сам есть состояние. Если результат верен, это значит, что флажок установлен, поэтому вы установите его на false и наоборот –

Смежные вопросы