如何在android中获取所选复选框项的值?

时间:2015-10-13 06:16:36

标签: android json android-asynctask

我正在开发类似应用程序(多项选择题)的测验,它从服务器接收问题并将答案集合发送到服务器按钮单击。为此我使用了包含TextView的ListView和4个选项的复选框项。我已成功编写代码以接收来自服务器的选项的问题。但现在我无法弄清楚如何在每个问题的4个选项框中获取特定选定复选框项的值?

activity_main.xml中

<RelativeLayout 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"
    tools:context="com.multiple.MainActivity" 
    >
    <!--android:background="@drawable/back"-->

 <TextView
     android:id="@+id/textview"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="@string/Title"
     android:background="@color/white"
     android:textColor="@color/col"
     android:gravity="center"
     android:textSize="30sp"
     />

   <ListView
       android:id="@+id/list"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_below="@+id/textview"
       android:layout_marginBottom="40sp"
       />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/finish"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />


</RelativeLayout>

list.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.multiple.MainActivity" 
    >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold"
        android:text="@string/Large"
        />
        <!--android:textColor="@color/white"-->
    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/textView1"
        android:text="@string/Checkbox"
        android:textSize="25sp"
        android:background="@color/white"
        android:textColor="@color/lightblue"
        android:focusable="false"
        />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/checkBox1"       
        android:text="@string/Checkbox"
        android:textColor="@color/lightblue"
        android:textSize="25sp"
        android:focusable="false"
        />
    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/checkBox2"
        android:textColor="@color/lightblue"
        android:text="@string/Checkbox"
        android:textSize="25sp"
        android:focusable="false"
        />
    <CheckBox
        android:id="@+id/checkBox4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/checkBox3"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:text="@string/Checkbox"
        android:textColor="@color/lightblue"
        android:textSize="25sp"
        android:focusable="false"
        />
</RelativeLayout>

MainActivity.java

package com.multiple;

import android.app.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;


public class MainActivity extends Activity
{

    private ListView listview;
    private Button finishbtn;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<HashMap<String, String>> collect = new ArrayList<HashMap<String, String>>();
        listview = (ListView) findViewById(R.id.list);
        finishbtn= (Button)findViewById(R.id.button);

        populate p = new populate();

        try {
            collect = p.execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    String[] str = new String[]{"first", "second", "third", "fourth", "fifth"};
        int[] val = new int[]{R.id.textView1, R.id.checkBox1, R.id.checkBox2, R.id.checkBox3, R.id.checkBox4};
        SimpleAdapter adapter = new SimpleAdapter(this, collect, R.layout.list, str, val);
        listview.setAdapter(adapter);

    listview.setOnClickListener(new ListView.OnClickListener()
    {

        @Override
        public void onClick(View v) {

        }
    });

}

    public class populate extends AsyncTask< String, Void,List<HashMap<String,String>> >
        {
            public List<HashMap<String,String>>  doInBackground(String... urls)
            {
                List<HashMap<String,String>> collect= new ArrayList<HashMap<String, String>>();
                    try
                    {


                        HttpClient client = new DefaultHttpClient();
                        HttpGet post = new HttpGet("http://192.168.10.116/file.json");
                        HttpResponse res= client.execute(post);
                        HttpEntity entity = res.getEntity();

                        String response = EntityUtils.toString(entity);



                        JSONObject obj = new JSONObject(response);
                        JSONArray jsonArray = obj.optJSONArray("multiple");

                            Log.i("size of the array",String.valueOf(jsonArray.length()));

                       ArrayList<JSONObject>  array = new ArrayList<JSONObject>();

                        for(int i=0; i < jsonArray.length(); i++)
                        {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            array.add(jsonObject);

                        }

                        for(int i=0;i<array.size();i++){
                            JSONObject jsonObject = array.get(i);
                            String question = jsonObject.optString("question").toString();
                            String c1 = jsonObject.optString("choice1").toString();
                            String c2 = jsonObject.optString("choice2").toString();
                            String c3 = jsonObject.optString("choice3").toString();
                            String c4 = jsonObject.optString("choice4").toString();

//                            Log.i("asdfas",question);
//                            Log.i("second",c1);
//                            Log.i("third",c2);
//                            Log.i("fourth",c3);
//                            Log.i("fifth",c4);

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

                            map.put("first",question);
                            map.put("second",c1);
                            map.put("third",c2);
                            map.put("fourth",c3);
                            map.put("fifth",c4);

                            collect.add(map);
                        }


    }

                    catch(IOException ex){}

                    catch(JSONException ex){}

                return  collect;
            }


        }
}

为简单起见,我还存储了我的应用程序的图像 Application layout

4 个答案:

答案 0 :(得分:0)

Listview不支持onclicklistener。使用onitemclicklistener如下

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
{
CheckBox checkbox1 = (CheckBox) view.findViewByid(R.id.checkbox1);
CheckBox checkbox2 = (CheckBox) view.findViewByid(R.id.checkbox2);
CheckBox checkbox3 = (CheckBox) view.findViewByid(R.id.checkbox3);
CheckBox checkbox4 = (CheckBox) view.findViewByid(R.id.checkbox4);
if(checkbox1 .isChecked())
      String checked = checkbox1.getText().tostring()
if(checkbox2 .isChecked())
      String checked = checkbox2.getText().tostring()
if(checkbox3 .isChecked())
      String checked = checkbox3.getText().tostring()
if(checkbox4 .isChecked())
      String checked = checkbox4.getText().tostring()
            }
        });

答案 1 :(得分:0)

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            str = "";
            str = (SimpleAdapter.adp_Str).get(arg2).toString();

        }
适配器类中的

将str []声明为static str []         });

答案 2 :(得分:0)

首先找到是否通过 isChecked()选中复选框,然后获取private void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if ((e.Row.RowType == DataControlRowType.DataRow)) { DropDownList ddl = ((DropDownList)(e.Row.FindControl("DropDownList3"))); ddl.SelectedIndexChanged += new System.EventHandler(this.ddlChange); } } private void ddlChange(object sender, EventArgs e) { DropDownList ddl = ((DropDownList)(sender)); GridViewRow row = ddl.NamingContainer; if ((ddl.SelectedItem.Text == "Y")) { row.Cells[6].Text = "0"; } else { // do what You want } } 中的值。

String

如果您的问题仅支持一个答案,则可以使用String answer; if(mycheckbox.isChecked()) { answer=mycheckbox.getText().toString(); } 来实现此目的。关于RadioButton的链接

http://www.mkyong.com/android/android-radio-buttons-example/

答案 3 :(得分:0)

我猜你按完成按钮后会收集答案。 1)您需要遍历listview中的相对布局,然后遍历相对布局中的复选框,并使用与每个复选框对应的isChecked()条件存储值,并获取相应的值。

您应该在完成按钮onclick listener中实现此功能。

int count = listview.getAdapter().getCount();
for(int i=0;i<count;i++){
   RelativeLayout relLayout = listview.getChildAt(i);
   for(int i=0;i< relLayout.getChildCount();i++){
      View v = relLayout.getChildAt(i);
      if(v instanceof CheckBox){
          CheckBox c = (CheckBox)v;
          if(c.isChecked()){
              String c = c.getText().tostring();
              //Add value to answers array or do processing
          }
      }
   }
}