android - 如何动态排序可排序 TableView 库中的列?

标签 android tableview

我正在使用 Sortable TableView 库来创建具有排序功能的表结构。库如下:

https://github.com/ISchwarz23/SortableTableView

我有 JSON 响应,我在其中获取表头和表体。我在表格中填充了标题和正文:

String[] myarray = new String[goalData.getTableheaderList().size()];

for (int i = 0; i < goalData.getTableheaderList().size(); i++) {

    myarray[i] = goalData.getTableheaderList().get(i).getName();

    if (goalData.getTableheaderList().get(i).isSort()) {

        int index = GoalsUtils.getIndex(goalData.getTableBodyList().get(0),
                goalData.getTableheaderList().get(i).getKey());

        setColumnComparator(i, TableComparator.getBodyComparator(index));

    }
}

如您所见,我使用数组来显示标题,正文也以相同的方式在不同的代码中显示。此外,我还在循环本身中使用了 Column Comparator 来根据数据对列进行排序。这是我的表比较器类:

public final class TableComparator {

private static int headerIndex;

private TableComparator() {
    //no instance
}

public static Comparator<List<TableBody>> getBodyComparator(int index) {
    headerIndex = index;
    return new BodyComparator();
}

private static class BodyComparator implements Comparator<List<TableBody>> {

    @Override
    public int compare(final List<TableBody> body1, final List<TableBody> body2) {
        return body1.get(headerIndex).getValue().compareTo(body2.get(headerIndex).getValue());
    }
}

现在的问题是我总是在上面的代码中修复 headerIndex。我的问题是如何动态获取它。有谁知道如何检测此库中的标题点击,或者我们如何在标题列点击时始终使 headerIndex 不同?任何帮助将不胜感激。

最佳答案

我能够解决我的问题。所以如果有人需要,我会发布答案。所以我使用 headerIndex 对列进行排序。在库中,columnComparator 类使用静态方法进行排序。我用下面的代码实现了动态排序:

    String[] headerArray = new String[headers.size()];
    for (int i = 0; i < headers.size(); i++) {
        int index = GoalsUtils.getIndex(body.get(0), headers.get(i).getKey());
        if (headers.get(i).isSort()) {
            setColumnComparator(i, new TableComparator(index));
        }
    }

和我的 TableComparator 类如下:

public final class TableComparator implements Comparator<List<TableBody>> {

private int headerIndex;

public TableComparator(int index) {
    headerIndex = index;
}

@Override
public int compare(final List<TableBody> body1, final List<TableBody> body2) {
    return body1.get(headerIndex).getValue().compareTo(body2.get(headerIndex).getValue());
}

编码愉快!

关于android - 如何动态排序可排序 TableView 库中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41342886/

相关文章:

java - 显示弹出窗口一次?

android - 使用没有 mediaextractor 的 mediacodec 的 MP3 解码失败

自定义 View 中的 Android 动画矩形

ios - UITableView 滑动手势需要近乎完美的精度

iOS7 表格索引显示为白色条

Xcode swift : My unwind segue doesn't add to my tableView

android - 从另一个 xml 获取 linearLayout Android

android - 如何在像素级操作图像并从图像中提取信息?

css - JavaFX TableView : howto move conditional cell styles to FXML/CSS?

ios - 使用每个新条目将新条目添加到表格顶部的表格 View Controller