选择单选按钮后,可平滑滚动到列表视图中的下一个项目

时间:2018-08-20 02:15:41

标签: java android listview android-viewholder android-radiogroup

在用户单击单选组中的“是”或“否”单选按钮后,如何平滑滚动到列表视图中的下一项。 例如。如果用户对第一个问题回答是或否,则应平滑滚动到第二个问题。 我找到了下面的代码,它正在使用静态位置值,但是我不知道如何在选择单选组(是或没有单选按钮)时滚动到下一个索引(下一个问题)。

 int index = 0;
    int h1 = simpleListView.getHeight();
    int h2 = simpleListView.getHeight();
    int duration=500;
    simpleListView.smoothScrollToPositionFromTop(index+4, h1/2 - h2/2, duration);

1)MainActivity_.class:-----------------

public class MainActivity_ extends AppCompatActivity {

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

@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;
            int index_first_unanswered = 0;
            List<Integer> backgroundColor = new ArrayList<Integer>(); // new
            if(customAdapter != null){
                for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
                    if(customAdapter.getSelectedAnswers().get(i).equals("3")){
                        if(!found_unanswered) { // new
                            found_unanswered = true;
                            index_first_unanswered = i; // new
                        }
                        backgroundColor.add(Color.RED); // new
                    }else{ // new
                        backgroundColor.add(Color.WHITE);
                    }
                }
            }

                if(!found_unanswered) {
                    Toast.makeText(getApplicationContext(), "All Answered", Toast.LENGTH_LONG).show();
                    customAdapter.setBackgroundColor(backgroundColor); // new
                    //Go to other activity
                }else{ // new
                    Toast.makeText(getApplicationContext(), "Found Unanswered", Toast.LENGTH_LONG).show();
                    if(customAdapter != null && lv != null){
                        customAdapter.setBackgroundColor(backgroundColor);
                        lv.smoothScrollToPosition(index_first_unanswered);
                    }
                }
        }
    });

    clear = (Button) findViewById(R.id.clear);
    clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (customAdapter != null) {
                customAdapter.clearSelectedAnswers();
            }
        }
    });

}


}

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

public class CustomAdapter extends BaseAdapter {

Context context;
String[] questionsList;
LayoutInflater inflter;
private List<String> selectedAnswers;
private List<Integer> backgroundColor; // new


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

@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]);
    question.setBackgroundColor(backgroundColor.get(i)); // new

    // initialize/re-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.
        rg.clearCheck(); // new
        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);
            //Toast.makeText(context , (checkedId == R.id.yes)?"yes":"no" , Toast.LENGTH_LONG).show();
            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;
                default: // new
                    rb_yes.setBackgroundColor(Color.GRAY);
                    rb_no.setBackgroundColor(Color.GRAY);
                    selectedAnswers.set(i, "3");
                    break;
            }
        }
    });

    return view;
}

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

public void clearSelectedAnswers(){
    selectedAnswers = new ArrayList<String>();
    backgroundColor = new ArrayList<Integer>();
    for (int i = 0; i < questionsList.length; i++) {
        selectedAnswers.add("3");
        backgroundColor.add(Color.WHITE); // new
    }
    this.notifyDataSetChanged();
}

public void setBackgroundColor(List<Integer> backgroundColor_){ // new
    this.backgroundColor = backgroundColor_;
    this.notifyDataSetChanged();
}

}

3)layout_8.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:weightSum="100"
android:orientation="vertical">

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

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_weight="10"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:orientation="horizontal">

    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Submit"
        android:layout_toStartOf="@id/v"
        android:textAllCaps="false"
        android:id="@+id/submit"/>

    <View
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:id="@+id/v"
        android:layout_centerInParent="true">
    </View>

    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Clear"
        android:layout_toEndOf="@id/v"
        android:textAllCaps="false"
        android:id="@+id/clear"/>

</RelativeLayout>

</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>

2 个答案:

答案 0 :(得分:1)

尝试以下操作:

1)CustomAdapter.class:--------

public class CustomAdapter extends BaseAdapter {

Context context;
String[] questionsList;
LayoutInflater inflter;
private List<String> selectedAnswers;
private List<Integer> backgroundColor;


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

@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, final ViewGroup viewGroup) {

    View view = convertView;

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

    final LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll); // new

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

    // initialize/re-restore UI Radio Button State
    final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
    final RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
    final 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.
        rg.clearCheck();
        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);
            //Toast.makeText(context , (checkedId == R.id.yes)?"yes":"no" , Toast.LENGTH_LONG).show();
            switch (checkedId) {
                case R.id.yes:
                    rb_yes.setBackgroundColor(Color.GREEN);
                    rb_no.setBackgroundColor(Color.GRAY);
                    selectedAnswers.set(i, "1");
                    scrollToNext((ListView) viewGroup, ll, i , 1); // new
                    break;
                case R.id.no:
                    rb_yes.setBackgroundColor(Color.GRAY);
                    rb_no.setBackgroundColor(Color.BLACK);
                    selectedAnswers.set(i, "2");
                    scrollToNext((ListView) viewGroup, ll, i , 1); // new
                    break;
                default:
                    rb_yes.setBackgroundColor(Color.GRAY);
                    rb_no.setBackgroundColor(Color.GRAY);
                    selectedAnswers.set(i, "3");
                    break;
            }
        }
    });

    return view;
}

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

public void clearSelectedAnswers(){
    selectedAnswers = new ArrayList<String>();
    backgroundColor = new ArrayList<Integer>();
    for (int i = 0; i < questionsList.length; i++) {
        selectedAnswers.add("3");
        backgroundColor.add(Color.WHITE);
    }
    this.notifyDataSetChanged();
}

public void setBackgroundColor(List<Integer> backgroundColor_){
    this.backgroundColor = backgroundColor_;
    this.notifyDataSetChanged();
}

private void scrollToNext(ListView parent , LinearLayout item , int index , int which) { // new

    // added two cases choose between one or two and delete the other one.
    int duration = 500;
    switch (which) {
        case 1:
            parent.smoothScrollToPositionFromTop((index + 1), item.getTop() - (parent.getHeight() / 2) + (parent.getHeight() / 2), duration);
            break;
        case 2:
            parent.smoothScrollToPositionFromTop((index + 1), (parent.getHeight() / 2) - (item.getHeight() / 2), duration);
            break;
        default:
            parent.smoothScrollToPositionFromTop((index + 1), item.getTop() - (parent.getHeight() / 2) + (parent.getHeight() / 2), duration);
            break;
    }

}

}

2)list_items.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="wrap_content"
android:id="@+id/ll"
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>

3)在上面的代码中,我添加了一个名为scrollToNext(...)的函数。在此功能内,您必须有两种滚动方式,因此在确定最适合您的滚动方式后,移除开关盒并直接调用parent.smoothScrollToPositionFromTop(...)。

答案 1 :(得分:1)

使接口进入适配器类,以这种方式处理点击事件。

    onRadioItemClick  onRadioItemClick;
interface onRadioItemClick{
    void onCheck(String str); // if you want pass any data when you need
}

public void setOnRadioItemClick(GalleryAdater.onRadioItemClick onRadioItemClick) {
    this.onRadioItemClick = onRadioItemClick;
}

在单击单选按钮后,以这种方式放置值界面。

        case R.id.yes:
    rb_yes.setBackgroundColor(Color.GREEN);
    rb_no.setBackgroundColor(Color.GRAY);
    onRadioItemClick.onCheck(selectedAnswers.get(i);

该适配器绑定到列表视图之后,然后在下面的代码中调用。

  galleryAdater.setOnRadioItemClick(new GalleryAdater.onRadioItemClick() {
        @Override
        public void onCheck(String str) {
            stringsList.set(strings.indexOf(str),"1");
            galleryAdater.notifyDataSetChanged();

        }
    });