【问题标题】:Not able to update listview items color in background无法在后台更新列表视图项目颜色
【发布时间】:2016-03-11 14:11:04
【问题描述】:

当我尝试根据我的数据库更新我的列表视图项目颜色时。我正在制作一个考勤应用程序,它允许老师标记出席或缺席。当他们标记出勤时,会根据标记的出勤自动生成一个偏好文件,并将颜色更改为红色或绿色。这不是永久性的,我已经制作了一个按钮,该按钮将检查偏好文件哪个学生在场或不在场,如果他在场,将他的名字更改为绿色,否则红色它工作得很好。但问题是我希望它自动检查后台并且不想一直按下按钮。 这是我正在工作的按钮代码,但我希望它在后台自动执行...

public void check(View view) {


    //getting everything from table student
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    String formattedDate = simpleDateFormat.format(new Date());

    SharedPreferences data = getSharedPreferences(latestBranch + "(" + latestSection + ") - " + formattedDate, MODE_PRIVATE);


    ArrayList<String> attend = new ArrayList<String>();

    //making loop to get all students from studentslist
    for (int x = 0; x < studentsList.size(); x++) {

        attend.add(data.getString(studentsList.get(x).toString(), ""));

    }

    for (int y = 0;y < studentsList.size(); y++) {

        if (attend.get(y).toString().equals("Present")) {

            listView.getChildAt(y).setBackgroundColor(Color.GREEN);

        } else if (attend.get(y).toString().equals("Absent")) {

            listView.getChildAt(y).setBackgroundColor(Color.RED);

        }


    }
}

【问题讨论】:

    标签: android listview sharedpreferences


    【解决方案1】:

    使用 ListView,您需要为列表编写自定义适配器。创建一个扩展 ArrayAdapter.java 的类。将您在 listView 中创建的自定义适配器的对象设置为其适配器。

    覆盖 public View getView (int position, View convertView, ViewGroup parent)

    显示列表视图时调用此方法。您可以通过为每个位置设置视图的状态[文本、颜色、启用状态等属性]来重用视图。

    您将数据(数据数组)与适配器相关联。当数据数组发生变化时,请在适配器对象上调用notifyDataSetInvalidated()

    在每个位置的 getView 方法(如上所述)中,根据该位置的数据数组中的颜色设置颜色。

    代码:listView.getChildAt(y)是基于可见项目的,详情参考下面的另一个问题链接。

    Sometimes listView.getChildAt(int index) returns NULL (Android)

    对于具有覆盖 getView 方法的自定义适配器,我建议您阅读有关 android 中的视图持有者模式。

    【讨论】:

    • 兄弟你能详细说明一下吗?我不明白
    • @AnshumanKaushik 你可以看到 guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView 阅读“使用自定义 ArrayAdapter”部分。查看如何在 getView 方法中设置数据,同样您可以设置颜色。当适配器上的底层 ArrayList 调用 notifyDataSetInvalidated() 发生一些变化时。
    • 每当我按下该按钮来更改颜色时,它都会起作用,但是如果我的列表视图中的项目在屏幕上不可见,则会导致错误并且应用程序崩溃我应该如何修复它。
    • 不要在onclick方法中写改变颜色的代码。仅在适配器的 getView 方法中更改您的 LISTVIEW 项目 UI。在与您的按钮关联的 Click Listener 的 onclick 方法中,只需在适配器对象上调用 notifyDataSetChanged()。
    • 在 onClick() 方法中只需修改您拥有的数据数组,然后调用 notifyDataSetChanged() ,一切都会按照您的要求工作。
    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多