如何使用多个单选按钮从自定义列表视图中获取数据

时间:2015-05-09 10:16:09

标签: android eclipse android-layout classcastexception

我在这里经历了很多链接,但是我无法让我的东西工作。你能帮我从我的自定义列表中获取数据吗?

详细信息如下: - 我的自定义列表视图

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RadioGroup 
        android:id="@+id/radioGroup_option"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:orientation="vertical">
    <TextView 
        android:id="@+id/tv_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="false"/>

    <RadioButton 
        android:id="@+id/rb_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <RadioButton 
        android:id="@+id/rb_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    </RadioGroup>

</LinearLayout>

我通过UI填充List,其代码是: -

package com.example.customadapter;

import java.lang.reflect.Array;
import java.util.Arrays;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CustomAdapter extends ActionBarActivity {

    AddDataToArray mydata;
    EditText qstno,qstn,opt1,opt2;
    Button btn_save,btn_display;
    int questio_no;
    String question,option1,option2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_adapter);
        mydata=AddDataToArray.getInstance();
        qstno=(EditText)findViewById(R.id.edt_qstn_no);
        qstn=(EditText)findViewById(R.id.edt_add_qstn);
        opt1=(EditText)findViewById(R.id.edt_opt1);
        opt2=(EditText)findViewById(R.id.edt_opt2);
        btn_save=(Button)findViewById(R.id.btn_save);
        btn_display=(Button)findViewById(R.id.btn_display);
        btn_save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                questio_no=Integer.parseInt(qstno.getText().toString());
                question=qstn.getText().toString();
                option1=opt1.getText().toString();
                option2=opt2.getText().toString();
                System.out.println("Questio added in the UI --> "+ question);
                String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
                Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
                qstn.setText("");
                opt1.setText("");
                opt2.setText("");

            }
        });

        btn_display.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                for (int i=0;i<mydata.myQstnList.size();i++)

                {
                    System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
                    System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
                    //System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
                }

                Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
                startActivity(myIntent);


            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.custom_adapter, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

最后我从基础适配器制作了一个适配器,如下所示: -

    package com.example.customadapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MyAdapter extends BaseAdapter {

    private LayoutInflater mInflater;
    private List<Question> mQuestion;
    Context context;

    public MyAdapter(Context context,List<Question> mQuestion) {
        super();
        this.context=context;
        this.mQuestion = mQuestion;
        this.mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mQuestion.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mQuestion.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view;
        ViewHolder holder;

        if (convertView == null){
            view = mInflater.inflate(R.layout.customized_view, parent,false);
            holder = new ViewHolder();
            holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
            holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
            holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
            holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
            view.setTag(mQuestion);


        }else {
            view = convertView;
            holder = (ViewHolder)view.getTag();
        }
        Question qstnRef=mQuestion.get(position);
        holder.tv_qstn.setText(qstnRef.getQstn());
        holder.rb_opt1.setText(qstnRef.getOpt1());
        holder.rb_opt2.setText(qstnRef.getOpt2());

        holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                //List<Question> data =(List<Question>) group.getTag();
                //Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();

                int childCount=group.getChildCount();
                for (int i=0;i<childCount;i++){
                    RadioButton r_btn=(RadioButton)group.getChildAt(i);
                    if (r_btn.getId() == checkedId){
                        System.out.println(r_btn.getText().toString());
                    }
                }

            }
        });



        return view;
    }

    private class ViewHolder {
        public TextView tv_qstn;
        public RadioButton rb_opt1,rb_opt2;
        public RadioGroup rg;
    }


}

但是我试图获取我在UI中输入的这些数据,但我无法使其工作,请向我提供帮助!!!!

当前格式的代码给出了运行时错误: -

  

05-09 06:01:06.669:E / AndroidRuntime(2420):   java.lang.ClassCastException:无法转换android.widget.TextView   到android.widget.RadioButton

     

05-09 06:01:06.669:E / AndroidRuntime(2420):at   com.example.customadapter.MyAdapter $ 1.onCheckedChanged(MyAdapter.java:83)

1 个答案:

答案 0 :(得分:1)

group.getChildCount()返回3,因为它有3 child。但是1个孩子属于TextView,这就是你获得java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton

的原因

为了避免在类型转换之前使用instanceof进行类型检查。

这样做:

 int childCount=group.getChildCount();
   for (int i=0;i<childCount;i++){             
       if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
           RadioButton r_btn = (RadioButton) group.getChildAt(i);
           if (r_btn.getId() == checkedId) {
                 System.out.println(r_btn.getText().toString());
            }
       }
   }