控制状态的CheckBox [英] Control CheckBox status

查看:210
本文介绍了控制状态的CheckBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经取回使用JSON从远程数据库的数据和我创建这个数据的自定义的ListView。我有三个的TextView和一个CheckBox和它完美的作品。所以,我添加了一个按钮,将控制列表中选择项目,并最终在另一个活动转移所选项目。问题解决的建议,但如果我滚动列表中,选择的项目losts status.I认为这取决于从horder或适配器。有人能帮助我吗?这里是我的code

I have retrieved data from a remote db using json and i have created a custom listView with this data. I have three TextView and one CheckBox and it works perfectly. So, i have added a button that would control selected items in list and eventually transfer selected item in another activity. Problem was solved as suggested,but if i scroll list, selected items losts status.I think it depends from horder or adapter. Can someone help me? Here is my code

public class Activity2 extends ActionBarActivity implements OnItemClickListener {

TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;


private ProgressDialog pDialog;

private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";

JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity2);
    list = (ListView) findViewById(R.id.listView);
    currIntent = getIntent();
    txtLavorante = (TextView) findViewById (R.id.Lavorante);
    txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
    stampaValori();
    list_serv = new ArrayList<HashMap<String,String>>();
    getData();


}

@Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {

    CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
    TextView tv = (TextView) v.findViewById(R.id.textView);
    cb.performClick();
    if (cb.isChecked()) {
        checkedValue.add(tv.getText().toString());

        Log.i("Btn Test",""+checkedValue);
    } else if (!cb.isChecked()) {
        checkedValue.remove(tv.getText().toString());
    }
}

private void stampaValori() {

    String pkg = getApplicationContext().getPackageName();
    String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
    String tNome =  "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
    txtLavorante.setText(tNome);
    txtCodice.setText(tCode);
}

protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        serv_man = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<serv_man.length();i++){
            JSONObject c = serv_man.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String price = c.getString(TAG_PRICE);
            String time = c.getString(TAG_TIME);


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

            persons.put(TAG_ID,id);
            persons.put(TAG_NAME,name);
            persons.put(TAG_PRICE,price);
            persons.put(TAG_TIME,time);

            list_serv.add(persons);
        }


        list = (ListView) findViewById(R.id.listView);
        list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
        list.setOnItemClickListener(Activity2.this);
        Button b= (Button) findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               // Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
                Log.i ("Test ",""+checkedValue);
            }
        });


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

}

public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://www.example.com/.php");

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                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 + "\n");
                }
                result = sb.toString();
                Log.i ("Servizi","serv:"+result);

            } catch (Exception e) {
                // Oops
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Activity2.this);
            pDialog.setMessage("Obtaining list...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }


        @Override
        protected void onPostExecute(String result){
            pDialog.dismiss();
            myJSON=result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}




    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity2, menu);
    return true;
}



    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

ListatoAdapter

ListatoAdapter

public class ListatoAdapter extends BaseAdapter {

private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;


public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv)  {
    super();
    this.context = context;
    this.dataList = list_serv;
    itemChecked = new boolean [dataList.size()];

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

@Override
public Object getItem(int position) {
    return null;
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    if (convertView == null) {

        convertView = inflater.inflate(R.layout.prenota_serv, null);
        holder = new ViewHolder();
        holder.service = (TextView)convertView.findViewById(R.id.et_serv);
        holder.id = (TextView)convertView.findViewById(R.id.et_id);
        holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
        holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
        holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.service.setText(dataList.get(position).get("Descrizione"));
    holder.id.setText(dataList.get(position).get("ID"));
    holder.costo.setText(dataList.get(position).get("Costo"));
    holder.durata.setText(dataList.get(position).get("Durata_m"));
    holder.Ceck.setChecked(false);

    if (itemChecked[position])
        holder.Ceck.setChecked(true);
    else
        holder.Ceck.setChecked(false);

    holder.Ceck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (holder.Ceck.isChecked())
                itemChecked[position] = true;

            else
                itemChecked[position] = false;
            Log.i("Adapter Test",""+itemChecked[position]);
        }
    });
    return convertView;
}

class ViewHolder {
    TextView service;
    TextView id;
    TextView costo;
    TextView durata;
    CheckBox Ceck;
}

}

Activity2.xml

Activity2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">

<TextView android:text="hello_word" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/Lavorante"
    android:textStyle="bold"
    android:textSize="22dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_gravity="right" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/CodiceLavorante"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:visibility="invisible" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView" />

prenota_serv.xml

prenota_serv.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Servizio:"
    android:textSize="7pt"
    android:id="@+id/tv_serv"
    android:layout_alignBottom="@+id/tv_id"
    android:layout_alignLeft="@+id/tv_id"
    android:layout_alignStart="@+id/tv_id" />
<EditText
    android:background="@android:drawable/editbox_background"
    android:layout_height="wrap_content"
    android:layout_width="190dip"
    android:id="@+id/et_serv"
    android:layout_gravity="center_horizontal"
    android:textSize="7pt"
    android:layout_alignBottom="@+id/et_id"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Costo Euro:"
    android:textSize="7pt"
    android:id="@+id/tv_cost"
    android:layout_below="@+id/et_serv"
    android:layout_alignLeft="@+id/tv_serv"
    android:layout_alignStart="@+id/tv_serv" />
<EditText
    android:background="@android:drawable/editbox_background"
    android:layout_height="wrap_content"
    android:layout_width="120dip"
    android:id="@+id/et_costo"
    android:layout_gravity="center_horizontal"
    android:layout_below="@+id/et_serv"
    android:layout_alignLeft="@+id/et_serv"
    android:layout_alignStart="@+id/et_serv"
    android:textSize="7pt" />
<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Durata min:"
    android:textSize="7pt"
    android:id="@+id/tv_dur"
    android:layout_below="@+id/et_costo"
    android:layout_alignLeft="@+id/tv_cost"
    android:layout_alignStart="@+id/tv_cost" />
<EditText
    android:background="@android:drawable/editbox_background"
    android:layout_height="wrap_content"
    android:layout_width="70dip"
    android:id="@+id/et_dur"
    android:layout_gravity="center_horizontal"
    android:textSize="7pt"
    android:layout_alignTop="@+id/tv_dur"
    android:layout_alignLeft="@+id/et_costo"
    android:layout_alignStart="@+id/et_costo" />
<TextView
    android:layout_marginTop="5dip"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Nr:"
    android:layout_marginLeft="5dip"
    android:layout_marginRight="9dip"
    android:layout_alignParentLeft="true"
    android:textSize="10pt"
    android:id="@+id/tv_id"
    android:visibility="invisible" />
<EditText
    android:background="@android:drawable/editbox_background"
    android:layout_height="wrap_content"
    android:layout_width="70dip"
    android:id="@+id/et_id"
    android:layout_gravity="center_horizontal"
    android:layout_alignTop="@+id/tv_id"
    android:layout_alignLeft="@+id/et_serv"
    android:layout_alignStart="@+id/et_serv"
    android:enabled="false"
    android:elegantTextHeight="false"
    android:visibility="invisible" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="CheckBox"
    android:layout_below="@+id/tv_dur"
    android:layout_alignRight="@+id/et_serv"
    android:layout_alignEnd="@+id/et_serv" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/textView"
    android:layout_alignParentBottom="true"
    android:layout_alignLeft="@+id/tv_dur"
    android:layout_alignStart="@+id/tv_dur" />

推荐答案

当用户选择一个复选框,将其相应的数据到list.and列表发送捆绑按钮click.and收到它的另一个活动关键的。

when user select a check box, put its corresponding data to a list.and send the list in bundle on button click.and receive it on another activity with the key.

您需要创建一个像列表。

you need to create a list like.

ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv)  {
    super();
    this.context = context;
    this.dataList = list_serv;
    list_selected = new ArrayList<HashMap<String, String>>();

}

改变监听器。

holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
                HashMap<String,String> data = dataList.get(position);
                if(isChecked){
                      addToSelected(data);

                }else{
                      removeSelected(data);
                }

            }
     });

    private void addToSelected(HashMap contact){

    if(!list_selected.contains(contact))list_selected.add(contact);
    }
    private boolean removeSelected(HashMap contact){

        return list_selected.remove(contact);
    }    

    public ArrayList<HashMap<String, String>> getSelectedItems(){
    return list_selected; 
    }

从活动清单 adapter.getSelectedItems();

在您的活动宣告它作为全球

declare it in your activity as global

ListatoAdapter adapter;

组适配器以这种方式。

set adapter in this way.

adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);

和获得按钮单击作为列表。

and get the list in button Click as.

ArrayList<HashMap<String,String> list = adapter.getSelectedItems();

这篇关于控制状态的CheckBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆