RadioButton状态和Button验证

时间:2018-06-28 07:18:04

标签: android

我面临两个问题。

  1. 单选按钮处于单选组丢失状态:当我单击“是”或“否”并向下滚动列表视图时,它会松开选中的单选按钮值。我尝试了多种方法来解决它,但无法实现。

  2. 提交按钮验证(请参阅图四):问题列表,用户应在单击提交按钮之前选择是或否,如果用户单击提交按钮但未选择是或否,则应向他们发送敬酒消息。所有问题均应选择是或否。更具体地说,每个无线电组应给我是或否,而不是空字符串。 预先感谢。

自定义适配器

public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
    this.context = context;
    this.questionsList = questionsList;
    selectedAnswers = new ArrayList<>();
    for (int i = 0; i < questionsList.length; i++) {
        selectedAnswers.add("");
    }
    inflter = (LayoutInflater.from(applicationContext));
}
@Override
public int getCount() {
    return questionsList.length;
}
@Override
public Object getItem(int i) {
    return i;
}

@Override
public long getItemId(int i) {
    return i;
}
@Override
public int getViewTypeCount() {
    return questionsList.length;
}

@Override
public int getItemViewType(int i) {

    return i;
}

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    view = inflter.inflate(R.layout.list_items, null);
    TextView question = (TextView) view.findViewById(R.id.question);
    final RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
    final RadioButton no = (RadioButton) view.findViewById(R.id.no);
    final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (yes.isChecked()) {
                yes.setBackgroundColor(Color.GREEN);
                no.setBackgroundColor(Color.BLACK);
            }
            if (no.isChecked()){
                no.setBackgroundColor(Color.rgb(255,165,0));
                yes.setBackgroundColor(Color.BLACK);
            }
        }
    });

    yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if (isChecked)
                selectedAnswers.set(i, "1");
        }
    });

    no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                selectedAnswers.set(i, "2");
        }
    });
    question.setText(questionsList[i]);
    return view;
}

主要活动

public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit,submit1;
FileOutputStream fstream;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    questions = getResources().getStringArray(R.array.questions);
    simpleList = (ListView) findViewById(R.id.simpleListView);
    View footerView = getLayoutInflater().inflate(R.layout.footer,null);
    submit = (Button) footerView.findViewById(R.id.submit1);
    simpleList.addFooterView(footerView);
    View headerView = getLayoutInflater().inflate(R.layout.header, null);
    simpleList.addHeaderView(headerView);
    CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
    simpleList.setAdapter(customAdapter);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String message = "";
            for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
                message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
            }
            try {
                fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
                fstream.write(message.getBytes());
                fstream.close();
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                Intent inent = new Intent(v.getContext(), DetailsActivity.class);
                startActivity(inent);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

XML主布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/Black"
android:padding="10dp">
<RelativeLayout
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:background="@drawable/round_relativelayout"
    >
<ListView
    android:id="@+id/simpleListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@color/Black"
    android:dividerHeight="1dp"
    android:footerDividersEnabled="false"
    />
</RelativeLayout>

列出项目XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@color/LightGrey">
<!-- TextView for displaying question-->
<TextView
    android:id="@+id/question"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:padding="@dimen/activity_horizontal_margin"
    android:textColor="#000"
    android:textSize="30dp"
    android:text="Which is your most favorite?"
    />
<FrameLayout 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=".MainActivity"
    android:id="@+id/main">
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/yes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:background="@color/Black"
            android:button="@null"
            android:paddingHorizontal="30dp"
            android:paddingVertical="5dp"
            android:text="YES"
            android:textColor="@color/White"
            android:textSize="50dp" />
        <RadioButton
            android:id="@+id/no"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:background="@color/Black"
            android:button="@null"
            android:paddingHorizontal="30dp"
            android:paddingVertical="5dp"
            android:text="NO"
            android:textColor="@color/White"
            android:textSize="50dp" />
    </RadioGroup>
</FrameLayout>

Image one Image two Image three Image four with submit button

2 个答案:

答案 0 :(得分:0)

尝试以下操作:

1)MainActivity_.class:-----

public class MainActivity_ extends AppCompatActivity {

private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout8);

    questions = new String[10];

    for(int i = 0 ; i<10 ; i++){
        questions[i] = "Q " + i;
    }

    lv = (ListView) findViewById(R.id.lv);
    customAdapter = new CustomAdapter(getApplicationContext() , questions);
    lv.setAdapter(customAdapter);

    submit = (Button) findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean found_unanswered = false;
            if(customAdapter != null){
                for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
                    if(customAdapter.getSelectedAnswers().get(i).equals("3")){
                        found_unanswered = true;
                        break;
                    }
                }
            }

            if(!found_unanswered){
                Toast.makeText(getApplicationContext() , "All Answered" , Toast.LENGTH_LONG).show();
                //Go to other activity
            }
        }
    });

}

}

2)CustomAdapter.class:------

public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;

public CustomAdapter(Context applicationContext, String[] questionsList) {
    this.context = context;
    this.questionsList = questionsList;
    selectedAnswers = new ArrayList<>();
    for (int i = 0; i < questionsList.length; i++) {
        selectedAnswers.add("3");
    }
    inflter = (LayoutInflater.from(applicationContext));
}

@Override
public int getCount() {
    return questionsList.length;
}

@Override
public Object getItem(int i) {
    return questionsList[i];
}

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

@Override
public int getViewTypeCount() {
    return questionsList.length;
}

@Override
public int getItemViewType(int i) {
    return i;
}

@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {

    View view = convertView;

    if (convertView == null) {
        if (inflter != null) {
            view = inflter.inflate(R.layout.list_items, null);
        }
    }


    TextView question = (TextView) view.findViewById(R.id.question);
    question.setText(questionsList[i]);

    // initialize/ restore UI Radio Button State
    final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
    RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
    RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
    if(selectedAnswers.get(i).equals("1")){
        rg.check(R.id.yes);
        rb_yes.setBackgroundColor(Color.GREEN);
        rb_no.setBackgroundColor(Color.GRAY);
    }else if(selectedAnswers.get(i).equals("2")){
        rg.check(R.id.no);
        rb_yes.setBackgroundColor(Color.GRAY);
        rb_no.setBackgroundColor(Color.BLACK);
    }else{
      // no answer.
        rb_yes.setBackgroundColor(Color.GRAY);
        rb_no.setBackgroundColor(Color.GRAY);
    }

    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
            RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
            switch (checkedId){
                case R.id.yes:
                    rb_yes.setBackgroundColor(Color.GREEN);
                    rb_no.setBackgroundColor(Color.GRAY);
                    selectedAnswers.set(i, "1");
                    break;
                case R.id.no:
                    rb_yes.setBackgroundColor(Color.GRAY);
                    rb_no.setBackgroundColor(Color.BLACK);
                    selectedAnswers.set(i, "2");
                    break;
            }
        }
    });

    return view;
}

public List<String> getSelectedAnswers(){
    return selectedAnswers;
}

}

3)layout8.xml:------

<?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"
android:weightSum="100">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="80"
    android:id="@+id/lv">
</ListView>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/lv"
    android:layout_weight="20"
    android:text="Submit"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/submit"/>

</LinearLayout>

4)list_items.xml:-----

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
    android:id="@+id/question"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="#000"
    android:textSize="30dp"
    android:text="Which is your most favorite?"
    />
<FrameLayout 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=".MainActivity"
    android:id="@+id/main">
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/yes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:button="@null"
            android:paddingHorizontal="30dp"
            android:paddingVertical="5dp"
            android:text="YES"
            android:textSize="50dp" />
        <RadioButton
            android:id="@+id/no"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:button="@null"
            android:paddingHorizontal="30dp"
            android:paddingVertical="5dp"
            android:text="NO"
            android:textSize="50dp" />
    </RadioGroup>
</FrameLayout>

</LinearLayout>

答案 1 :(得分:0)

尝试一下。 使用ViewHolder,以免丢失数据集

自定义适配器类

     @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

         ViewHolder viewHolder;
if(view == null){
        view = inflter.inflate(R.layout.list_items, null);
        viewHolder = new ViewHolder();

        ViewHoldwe.question = (TextView) view.findViewById(R.id.question);
        viewHolder.yes = (RadioButton) view.findViewById(R.id.yes);
        viewHolder.no = (RadioButton) view.findViewById(R.id.no);
        viewHolder.rg = (RadioGroup) view.findViewById(R.id.radio_group);

view.setTag(viewHolder)
}else{
viewHolder = (ViewHolder) view.getTag();

        viewHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (viewHolder.yes.isChecked()) {
                    viewHolder.yes.setBackgroundColor(Color.GREEN);
                    viewHolder.no.setBackgroundColor(Color.BLACK);
                }
                if (viewHolder.no.isChecked()){
                    viewHolder.no.setBackgroundColor(Color.rgb(255,165,0));
                    viewHolder.yes.setBackgroundColor(Color.BLACK);
                }
            }
        });

        viewHolder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked)
                    selectedAnswers.set(i, "1");
            }
        });

        viewHolder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                    selectedAnswers.set(i, "2");
            }
        });
        question.setText(questionsList[i]);
}
        return view;
    }

设置私有内部类

    private class ViewHolder{
    RadioButton yes;
    TextView question;
    RadioButton no ;
    RadioGroup rg;

}