Android Studio入门实战 选课中心——解决滚动条 无法保持复选框选中状态

声明:此篇仅借鉴,大家依次按需拿取即可。 

图片资源就不上传了,本项目共有六本书的资源,自己加也行。

接下来内容敬请期待。

目录

效果图:

 重要点讲明:

        如何用Linerlayout布局

        如何解决滚动到下个界面时,复选框能保持选中状态。

知识点铺垫: 

思路:

记录弹框内容

按钮点击出现弹框:

知识铺垫:

思路:

//提示框模板(Dialog):

我遇见bug的解决方案:

        因为涉及到adapter,所以容易出现 

完整代码:


效果图:

 重要点讲明:

        如何用Linerlayout布局

             大概是这样的思路,linear布局中还嵌套了linear列表控件,所以分为两个布局文件。 

如何解决滚动到下个界面时,复选框能保持选中状态。

    知识点铺垫: 

        其实很简单,在java的数据结构中大家都学过map<String ,Object>

        Map是一个接口,即Interface Map<K,V>,其中K-key类型和V-value的类型。

 它的每个元素包含一个key对象和一个value对象,且在这两个对象之间存在一种映射的对应关系,所有从Map集合中访问元素时,只有指定了key就可以找到对应的value,因此key必须是唯一的且不能重复,当key相同时,后面的value值会覆盖之前的value值。

其实这个解释与python的键值对很像,取值逻辑也相似,不过还是不能混为一谈,大家可以联想记忆。

而Myadapter 中也用到了List<map<String,Object>>,用来映射数据,而context值上下文,你可以理解为布局文件,但是没有数据,如图所示:


而解决复选框再滚动过后不能保持选中状态,可以使用map<integer,boolean>类型映射并记录复选框的状态,其中第一个int类型是记录下标的,相当于boolean数组的逻辑。

        思路:

设置checkbox监听器,设置map<Integer,boolean>记录下标及选中情况,最后就将复选框状态改为选中(就是setcheck()事件件是要自主控制的)[  i 对应key ,  boolean对应value]

 //checkbox 监听器
        checkxuanke.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                tempMap.put(i, b);

            }
        });
        checkxuanke.setChecked(tempMap.get(i));

        记录弹框内容

并且记录下标映射到“cname"的数据,如果没有选中,但之前选过的用字符串replace。如图:

按钮点击出现弹框:

        知识铺垫:

        大家配置btn 按钮,很有可能出现Null 空指针的报错,其主要原因就是这个页面没有btn控件 view = View.inflate(context, R.layout.list_item1_layout, null);所以大家配置要在主页面的上下文,也就是主类里的onCreated()函数中,按钮点击事件绑定adapter.showDialog(view) 函数,就实现了弹窗。

        其次,弹窗内容获取,和设置复选框选中事件,都必须在MyAdapter类的getview(参数)中,因为其中view是list_item1_layout.xml,不是主类。

        思路:

       get弹窗Message:

 public String getmessage(String temp) {
         for (int pos = 0; pos < datas.size(); pos++) {
             if (tempMap.get(pos) == true) {
                 temp += datas.get(pos).get("cname").toString()+" ;";

             } else {
                 temp.replace(datas.get(pos).get("cname").toString(), " ");
             }

         }
         return temp;
     }

        之后,再用Dialog弹窗:

public void showDialog(View view){
         AlertDialog.Builder builder=new AlertDialog.Builder(context);
         builder.setTitle("选课提示");

         //选课message获取
         String temp ="选择的课程是 : ";

         builder.setMessage(getmessage(temp));

         builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {

             }
         });
         AlertDialog dialog=builder.create();
         dialog.show();
     }

//提示框模板(Dialog):

 public void showDialog(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("标题");
        builder.setMessage("提示内容");
        builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }

我遇见bug的解决方案:

        因为涉及到adapter,所以容易出现 

        /*

                偷懒*2

                */

完整代码:

如果对你有用的话,给个小赞吧 >_<

MainActivity2.java:

package com.example.myapplication5;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MainActivity2 extends Activity {

    //写入课程、课时、图片 列表数据
    //六本书数据
    private  String[] cname = {"Java编程语言","C语言程序设计","JavaEE开发","js程序高级开发","python高级程序设计","深度学习与mind实践"};
    private String[] ctimes = {"64学时","48学时","96学时","64学时","48学时","96学时"};
    //记得补上,图片数组。
    private int[] image = {R.drawable.book1,R.drawable.book2,R.drawable.book3,R.drawable.book4,R.drawable.book5,R.drawable.book6};

    private ListView lsview;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lsview = findViewById(R.id.lsview);
        btn = findViewById(R.id.button);
        //建立列表

        List<Map<String,Object>> course_list = new ArrayList<Map<String,Object>>();
        for(int i=0;i<cname.length;i++){
            Map<String, Object> list_item = new HashMap<String,Object>();

            list_item.put("cname",cname[i]);
            list_item.put("ctimes",ctimes[i]);

            list_item.put("image",image[i]);
            course_list.add(list_item);
        }
        MyAdapter adapter = new MyAdapter(course_list,this);
        lsview.setAdapter(adapter);

        //按钮事件
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.showDialog(view);

            }
        });


    }


    /*
    public void showDialog(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("标题");
        builder.setMessage("提示内容");
        builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }

     */
}
 class MyAdapter extends BaseAdapter{
    private List<Map<String, Object>> datas;
    private Context context;
    //用hashmap 存储checkbox的选中状态
    private HashMap<Integer, Boolean> tempMap;

    //构造类
    public MyAdapter(List<Map<String,Object>> datas,Context context){
        this.datas = datas;
        this.context = context;
        tempMap = new HashMap<Integer,Boolean>();
        for (int i =0;i<datas.size();i++){
            tempMap.put(i,false);
        }
    }

    @Override
    public int getCount() {
        return datas.size();
    }
//返回类型是object。
    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = View.inflate(context, R.layout.list_item1_layout, null);


        //绑定控件
        TextView txtCourse = view.findViewById(R.id.textView);
        TextView txtTimes = view.findViewById(R.id.textView2);
        ImageView image = view.findViewById(R.id.imageView2);
        CheckBox checkxuanke = view.findViewById(R.id.checkBox1);
        // Button btn = view.findViewById(R.id.button1);
        //在list_item1_layout没有button1 而在主页面 ,adapter 传的view是list的

        //传递数据
        txtCourse.setText(datas.get(i).get("cname").toString());
        txtTimes.setText(datas.get(i).get("ctimes").toString());
        image.setImageResource((Integer) (datas.get(i).get("image")));

        //checkbox 监听器
        checkxuanke.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                tempMap.put(i, b);

            }
        });
        checkxuanke.setChecked(tempMap.get(i));

        //按钮跳出提示框
        /*
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("标题");
        builder.setMessage(temp);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();



    }
    */
        //btn.setOnClickListener(view1 -> {
            /*
            for (int pos=0;pos<datas.size();pos++){
                if (tempMap.get(pos)==true){
                    temp+=datas.get(pos).toString();

                }else{
                    temp.replace(datas.get(pos).toString()," ");
                }

             */
        //  });


        return view;
    }
     public void showDialog(View view){
         AlertDialog.Builder builder=new AlertDialog.Builder(context);
         builder.setTitle("选课提示");

         //选课message获取
         String temp ="选择的课程是 : ";

         builder.setMessage(getmessage(temp));

         builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {

             }
         });
         AlertDialog dialog=builder.create();
         dialog.show();
     }
     public String getmessage(String temp) {
         for (int pos = 0; pos < datas.size(); pos++) {
             if (tempMap.get(pos) == true) {
                 temp += datas.get(pos).get("cname").toString()+" ;";

             } else {
                 temp.replace(datas.get(pos).get("cname").toString(), " ");
             }

         }
         return temp;
     }
}

 activity_main.xml:

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

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="73dp"
        android:layout_weight="1"
        android:text="选课中心"
        android:textAlignment="center"
        android:textSize="20dp" />

    <ListView
        android:id="@+id/lsview"
        android:layout_width="match_parent"
        android:layout_height="668dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_weight="1"
        android:background="#93D8E1"
        android:text="提交" />
</LinearLayout>

list_item1_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<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">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="158dp"
        android:layout_height="208dp"
        tools:src="@drawable/book1"
        tools:srcCompat="@tools:sample/avatars" />

    <LinearLayout
        android:layout_width="248dp"
        android:layout_height="207dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="220dp"
            android:layout_height="48dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="课程"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="97dp"
            android:layout_height="41dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="30dp"
            android:text="学时"
            android:textSize="20dp" />

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="160dp"
            android:layout_marginTop="40dp"
            android:text="选课" />
        </LinearLayout>

    </LinearLayout>

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值