在Android应用程序中使用ArrayAdapter按字母排序的列表视图和字母部分

Yoa*_*oav 0 sorting android listview

我想要一个带有自定义adatper的listview,扩展ArrayAdapter,其中Type有Name字段(String).我想对Alphabitcly项目进行排序(这不是问题)然后放入字母部分.

例如:A Alpha Any ... C Child ...我墨水

此外 - 使用Paging从Web服务检索结果,因此当用户按下GetMoreResult按钮时,列表应相应更新 - notifyDataSetChanged将起作用吗?

Saa*_*ooq 8

我正在尝试同样的事情.我尝试使用Kasper提到的currentChar逻辑来完成它.看起来listView()调用并不总是按照您期望的顺序进行,因此效果不佳.我的解决方案是这样的:

在XML中添加一个具有可见性GONE的TextView,就像这样.这将是您的分隔符标签.

<TextView
    style="?android:attr/listSeparatorTextViewStyle"
    android:id="@+id/separator"
    android:layout_width="fill_parent"
    android:visibility="gone"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white" />
Run Code Online (Sandbox Code Playgroud)

注意:我使用Android标准分隔符样式.当然你可以自己做.

然后使用类似这样的方法向Adapter类添加一个布尔数组

/**
* Method takes the alphabetically sorted ArrayList as argument
*/        
private void assignSeparatorPositions(ArrayList<Items> items) {
        separatorAtIndex = new boolean[items.size()];
        char currentChar = 0;

        for (int i=0; i< items.size(); i++) {
            if ( itemss.get(i).getName().charAt(0) != currentChar ) {
                separatorAtIndex[i] = true;
            } else {
                separatorAtIndex[i] = false;
            }
            currentChar = items.get(i).getName().charAt(0);
        }

}
Run Code Online (Sandbox Code Playgroud)

最后你在getView()做这样的事情:

if ( separatorAtIndex[position] ) {
            holder.sectionHeader.setText(""+name.charAt(0));
            holder.sectionHeader.setVisibility(View.VISIBLE);
        } else {
            holder.sectionHeader.setVisibility(View.GONE);
}
Run Code Online (Sandbox Code Playgroud)

此方法的优点是,在添加单独的标题视图后,不需要您跟踪项目的新位置.