1. 程式人生 > >Android 單選介面卡(預設選中從資料庫中查出為True的選項)

Android 單選介面卡(預設選中從資料庫中查出為True的選項)

網上看了好多單選的案例,沒有看到說從資料庫查值的為單選的,自己最近又有這個需求,索性就寫一個吧
,雖然說現在都流行H5的了,但原生總會有些情況下需要做的吧
package com.cntaipu..Adapater;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import 
android.widget.CompoundButton; import android.widget.TextView; import com.cntaipu.R; import java.util.ArrayList; /** * Created by 1140 on 2018/2/10. */ public class FKAdapter extends BaseAdapter { private Activity activity;//上下文 private ArrayList<String> list; private LayoutInflater inflater
= null;//佈局匯入 private int temp = -1; public FKAdapter(Activity context, ArrayList<String> list) { this.activity = context; this.list = list; inflater = LayoutInflater.from(context); } @Override public int getCount() { return list.size(); } @Override
public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) {//當的第一次載入listView時候,convertView 為空 convertView = inflater.inflate(R.layout.sf_log_kinds_list, null);holder = new ViewHolder(); holder.fk = (TextView) convertView.findViewById(R.id.tv_fishLogKinds);//資訊 holder.cb = (CheckBox) convertView.findViewById(R.id.cb_choose_kind);//選擇 convertView.setTag(holder); } else {//取出holder holder = (ViewHolder) convertView.getTag(); } // 設定list的textView顯示 holder.fk.setText(list.get(position).split(":")[0]); // 根據isSelected 來設定checkbox的選中中狀況 holder.cb.setId(position);//對checkbox 的id 進行重新設定當前的position
//   根據資料庫查出狀態為true
if (list.get(position).split(":")[1].equals("1")) {
            holder.cb.setChecked(true);
        }

        // 根據isSelected來設定checkbox的選中狀況
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {//實現checkbox的單選功能,同樣適用於radiobutton
if (temp != -1&&temp != compoundButton.getId()) {
                            //找到上次點選的checkbox,並把它設定為false,對重新選擇時可以將以前的關掉
CheckBox tempCheckBox = (CheckBox) activity.findViewById(temp);
                            if (tempCheckBox != null) {
                                tempCheckBox.setChecked(false);
                            }
                    }
                    temp = compoundButton.getId();//儲存當前選中的checkbox的id值
}
            }
        });

        if (position == temp)//比對position和當前的temp是否一致
holder.cb.setChecked(true);
        else
holder.cb.setChecked(false);
        return convertView;

    }


    public static class ViewHolder {
        public TextView fk;
        public CheckBox cb;
    }
}