【问题标题】:Change color of a particular item in a listview as per the values from the database根据数据库中的值更改列表视图中特定项目的颜色
【发布时间】:2016-05-06 06:42:59
【问题描述】:

我有一个片段,即 ScheduledFragment,在那个片段中我有一个自定义列表视图。正在从服务器获取值并将这些值插入到列表项中。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View rootView = inflater.inflate(R.layout.fragment_scheduled, container, false);

    final ArrayList<CoursePojo> searchResults = GetSearchResults();


    final ListView lv1 = (ListView) rootView.findViewById(R.id.lvList2);

    lv1.setAdapter(new MyCustomCourseList(getActivity(), searchResults));
    lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            Object o = lv1.getItemAtPosition(position);
            String currentid = ids.get(position);
            String currentcourse = cs.get(position);

            CoursePojo fullObject = (CoursePojo) o;              

        }
    });
    return rootView;}

正在将值添加到数组列表中。 MyCustomCourseList 适配器类 getView() 如下所示

public View getView(int position, View convertView, ViewGroup parent) {
    View view=convertView;
    ViewHolder holder;
    if (convertView == null) {
    holder.relativeLayout=(RelativeLayout)convertView.findViewById(R.id.rel1);
    else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.relativeLayout.setBackgroundColor(convertView.getResources().getColor(R.color.textColorPrimary));

这是为我的整个自定义列表设置颜色。但我真正需要的是从服务器获取一些日期,我需要更改某些日期的列表项的背景颜色。在比较从服务器获得的日期和当前日期之后,我需要更改这些列表项的颜色。当前日期之前的日期必须以背景颜色“主要颜色”显示,当前日期之后的日期必须以颜色“次要颜色”显示

【问题讨论】:

    标签: android date listview android-fragments


    【解决方案1】:

    在 getView 中做一些日期比较,并以此为基础上色

    if(validateDate(new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault()).format(c.getTime()),rowItem.getApiDate))
        holder.relativeLayout.setBackgroundColor(convertView.getResources().getColor(R.color.textColorPrimary));
    else
       holder.relativeLayout.setBackgroundColor(convertView.getResources().getColor(R.color.textColorSecondary));
    

    【讨论】:

    • 如果它没有帮助你。你需要代码实现吗。
    • 嗨 pramod 感谢 rply,但它没有帮助我,因为当我尝试获取日期时它会抛出 unparsebale 异常,这是因为在 getView () 中我没有日期。如果您能给我一些代码实现,将不胜感激
    • 嗨 Pramod,我犯了一个小错误,我给日期格式错误导致了异常。现在它像魅力一样工作!!!
    【解决方案2】:

    您可以通过在片段和适配器之间创建通信来实现上述要求...我在下面列出了以下内容。

    • 将标签设置为相对布局
    • 在你的fragment类中实现了一个接口[这个接口将起到fragment和adapter之间的桥梁作用]
    • 在接口的方法中,您可以访问您的适配器类并做任何您想做的事情。

    【讨论】:

    • 您好,Attiq,感谢您的回复。我可以给我一些相同的示例代码
    • 我可以分享我的代码,但我认为您已经通过接受 Mishra 的回答解决了您的问题
    猜你喜欢
    • 2014-07-08
    • 2013-10-18
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多