You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据JSON返回的日期数据隐藏指定ListView列表项中的TextView

解决方案

你当前使用的默认SimpleAdapter仅支持基础文本赋值,要实现列表项控件的显隐控制、自定义样式,需要搭配SimpleAdapter.ViewBinder实现自定义绑定逻辑,同时优化JSON字段读取逻辑避免字段不存在时崩溃,具体修改如下:

1 修正JSON字段读取逻辑

原有jo.getString()方法在对应字段不存在时会直接抛出异常,改为使用optString()方法,字段不存在时默认返回空字符串,不会触发崩溃:

// 把原来的getString替换为optString
String titulo = jo.optString(Search_data_anuncios.KEY_titulo_anuncio_cliente, "");
String descripcion = jo.optString(Search_data_anuncios.KEY_descripcion_anuncio_cliente, "");
// 日期字段不存在时会返回空字符串
String fecha_creacion = jo.optString(Search_data_anuncios.KEY_fecha_creacion_anuncio_cliente, "");
String categoria_anuncio_cliente = jo.optString(Search_data_anuncios.KEY_categoria_anuncio_cliente, "");

2 给SimpleAdapter添加ViewBinder绑定逻辑

在创建SimpleAdapter之后、调用setAdapter之前,添加自定义ViewBinder逻辑,判断日期是否为空,控制TextView的显隐和样式:

ListAdapter adapter = new SimpleAdapter(
        PrimerActivity.this, list, R.layout.activity_anuncio_item_listview,
        new String[]{Search_data_anuncios.KEY_titulo_anuncio_cliente, Search_data_anuncios.KEY_descripcion_anuncio_cliente, Search_data_anuncios.KEY_fecha_creacion_anuncio_cliente, Search_data_anuncios.KEY_categoria_anuncio_cliente},
        new int[]{R.id.tv_titulo, R.id.tv_descripcion, R.id.tvclass});
// 新增自定义ViewBinder逻辑
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
    @Override
    public boolean setViewValue(View view, Object data, String textRepresentation) {
        if (view.getId() == R.id.tvclass) {
            String fecha = (String) data;
            TextView tvClass = (TextView) view;
            if (fecha.isEmpty()) {
                // 日期为空,隐藏TextView
                tvClass.setVisibility(View.GONE);
            } else {
                // 日期不为空,显示并设置自定义样式、背景
                tvClass.setVisibility(View.VISIBLE);
                tvClass.setText(fecha);
                // 设置自定义背景,替换为你自己的drawable资源
                tvClass.setBackgroundResource(R.drawable.custom_date_bg);
                // 还可以自定义文字颜色、大小等样式
                tvClass.setTextColor(Color.WHITE);
                tvClass.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            }
            // 返回true表示当前控件的绑定逻辑已自行处理,不需要SimpleAdapter再执行默认逻辑
            return true;
        }
        // 其他控件走默认绑定逻辑
        return false;
    }
});
anunt.setAdapter(adapter);

可选优化

如果后续列表逻辑更复杂(比如要加载图片、添加点击事件等),建议直接自定义BaseAdapter或者用RecyclerView替代ListView,扩展性和性能都更好。

内容的提问来源于stack exchange,提问作者Ciprian Sandu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:15:09