栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

安卓listview实练(json传递数据)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

安卓listview实练(json传递数据)

建立adapter包内含ChooseConstellaListAdapter(适配器)

建立bean包内含ConstellationBean实体类

建立utils通用工具包内含Constant类和JsonParse类

!!!!!!!清单文件一定要加权限!!!!!不然列表出不来

清单文件增加如下权限:

    
    
    

build.gradle中dependencies

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation files('libs\BaiduLBS_Android.jar')
    implementation files('libs\CCSDK.jar')
    implementation files('libs\glide-3.7.0.jar')
    implementation files('libs\gson-2.8.0.jar')
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'

}

libs下加入jar包

1、布局文件:

          包括两个(1)activity_main.xml为主要布局,里面包括列表标题、分割线和列表

                        (2)choose_constella_item.xml为列表布局

        activity_main.xml:




    
        
        
        
    
    

     choose_constella_item.xml:




    
    
    


2、Constant:

public class Constant {
    //使用本机ip
    public static final String WEB_SITE="http://10.20.123.214:8080/topline";
    //json文件
    public static final String REQUEST_CHOOSE_CONSTELLATION_LIST_URL="/choose_constellation_list_data.json";
}

    JsonParse:

public class JsonParse {
    private static JsonParse instance;
    private JsonParse(){
    }
    public static JsonParse getInstance(){
        if (instance==null){
            instance=new JsonParse();
        }
        return instance;
    }

    public List getConstellaList(String json){
        //使用gson库解析JSON数据
        Gson gson=new Gson();
        //创建一个TypeToken的匿名子类对象,并调用对象的getType()方法
        Type listType=new TypeToken>(){
        }.getType();
        //把获取到的信息集合存放到adList中
        List constellaList=gson.fromJson(json,listType);
        return  constellaList;
    }
}

3、ConstellationBean(内含四个私有属性和其set、get和toString方法另外要求序列化):

public class ConstellationBean implements Serializable {
    private int id;//星座id
    private String img;//星座选择界面的带色星座图标
    private String name;//星座名称
    private String date;//星座日期
}

4、ChooseConstellaListAdapter适配器:

public class ChooseConstellaListAdapter extends RecyclerView.Adapter implements View.OnClickListener {
    private List cbList;
    private Context context;
    private OnItemClickListener mOnItemClickListener = null;
    public ChooseConstellaListAdapter(Context context) {
        this.context = context;
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }
    public void setData(List cbList) {
        this.cbList = cbList;
        notifyDataSetChanged();
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
    {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.
                choose_constella_item, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(this);
        return viewHolder;
    }
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int i) {
        ConstellationBean bean = cbList.get(i);
        ((ViewHolder) holder).tv_contella_name.setText(bean.getName());
        ((ViewHolder) holder).tv_date.setText(bean.getDate());
        Glide
                .with(context)
                .load(bean.getImg())
                .error(R.mipmap.ic_launcher)
                .into(((ViewHolder) holder).iv_img);
        //将i保存在itemView的Tag中,以便点击时进行获取
        holder.itemView.setTag(i);
    }
    @Override
    public int getItemCount() {
        return cbList == null ? 0 : cbList.size();
    }
    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            //注意这里使用getTag方法获取position
            mOnItemClickListener.onItemClick(v, (int) v.getTag());
        }
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_contella_name, tv_date;
        public ImageView iv_img;
        public ViewHolder(View itemView) {
            super(itemView);
            tv_contella_name = (TextView) itemView.findViewById(R.id.tv_contella_name);
            tv_date = (TextView) itemView.findViewById(R.id.tv_date);
            iv_img = (ImageView) itemView.findViewById(R.id.iv_constella_img);
        }
    }
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}

5、MainActivity:

public class MainActivity extends AppCompatActivity {

    private ImageView iv_close;
    private ChooseConstellaListAdapter adapter;
    private OkHttpClient okHttpClient;
    public static final int MSG_CHOOSE_CONSTELLATION_OK = 1;//获取星座数据
    private MHandler mHandler;
    private RecyclerView recyclerView;
    private List list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new MHandler();
        okHttpClient = new OkHttpClient();
        getData();
        init();
    }
    private void init() {
        recyclerView = (RecyclerView) findViewById(R.id.rv_list);
        //这里用线性显示 类似于  ListView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ChooseConstellaListAdapter( this);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new ChooseConstellaListAdapter.
                OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("id", list.get(position).getId());
                setResult(RESULT_OK, intent);
                 MainActivity.this.finish();
            }
        });
    }
    
    class MHandler extends Handler {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case MSG_CHOOSE_CONSTELLATION_OK:
                    if (msg.obj != null) {
                        String result = (String) msg.obj;
                        list = JsonParse.getInstance().getConstellaList(result);
                        if (list != null) {
                            if (list.size() > 0) {
                                adapter.setData(list);
                            }
                        }
                    }
                    break;
            }
        }
    }
    private void getData() {
        Request request = new Request.Builder().url(Constant.WEB_SITE +
                Constant.REQUEST_CHOOSE_CONSTELLATION_LIST_URL).build();
        Call call = okHttpClient.newCall(request);
        //开启异步线程访问网络
        call.enqueue(new  Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Message msg = new Message();
                msg.what = MSG_CHOOSE_CONSTELLATION_OK;
                msg.obj = res;
                mHandler.sendMessage(msg);
            }


        });
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969513.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号