ListView项目排序/重新排序和保存更改?

时间:2012-02-21 10:28:08

标签: android android-listview commonsware-cwac

我有ListView我可以重新排序项目,但每次我退出应用程序并再次启动它时,订单将恢复为默认值。我很感激,如果有人能给我答案,也许还有一些我可以做到这一点的片段。

示例:我有两个项目和两个链接。谷歌和雅虎。我使用拖放和ArrayList。一切都很好,除了我不知道如何保存新订单。

我不知道是否还有其他方法可以重新排序这些项目。

我使用CWAC-TOUCHLIST来做到这一点。

这是我有多远:

    private static String[] items={"Google", "Yahoo"};

    private static String[] links={"http://google.com", "http://yahoo.com"};

    private IconicAdapter adapter=null;

    private IconicAdapter1 adapter2=null;

    ArrayList<String> array= new ArrayList<String>(Arrays.asList(items));

    private ArrayList<String> array2=
        new ArrayList<String>(Arrays.asList(links));

   /** Called when the activity is first created. **/
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TouchListView tlv=(TouchListView)getListView();
        adapter=new IconicAdapter();
        adapter2=new IconicAdapter1();
            setListAdapter(adapter);
        setListAdapter(adapter2);

        tlv.setOnItemClickListener(itemclick);
        tlv.setDropListener(onDrop);

   }

    private TouchListView.DropListener onDrop =
        new TouchListView.DropListener() {
            @Override
            public void drop(int from, int to) {
                String item=(String) adapter.getItem(from);

                adapter.remove(item);
                adapter.insert(item, to);

                String link=(String) adapter2.getItem(from);
                adapter2.remove(link);
                adapter2.insert(link, to);
            }
        };

    private TouchListView.OnItemClickListener itemclick =
        new TouchListView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view,
                int from, long id) {

                String item = adapter.getItem(from);

            Toast.makeText(getBaseContext(), "you pick: "+item,
                        Toast.LENGTH_SHORT).show();

                String link = adapter2.getItem(from);
                Intent showContent = new Intent(getApplicationContext(),
                        Web.class);
                showContent.setData(Uri.parse(link));
                startActivity(showContent);
            }
        };

有更聪明的方法吗?

1 个答案:

答案 0 :(得分:2)

您必须将列表及其订单保存到文件或数据库中。 应用程序启动时,您必须从保存的列表中初始化ListView。 当你拖动&amp;删除项目,您必须保存更改。

您需要更改的方法: 除了已经执行的操作之外,drop方法还应将更改存储在文件或数据库中。 您应该传递已保存的数组,而不是在IconicAdapter和IconicAdapter2构造函数(array&amp; array2)中传递的数组。

您可以在许多地方阅读如何将数据存储到文件或SQLite DB中。例如,你可以在这里找到一个很好的SQLite教程 - http://www.vogella.com/articles/AndroidSQLite/article.html#android_requisites(前四个部分是相关的,因为你不必使用ContentProvider)。 如果选择使用数据库,则可以创建包含以下列的表:item,link&amp;订购。在drop方法中,你必须更新顺序介于from和to之间的所有行的order列(或者如果列表不是太大,你可以简单地更新所有行并将顺序设置为索引。保存列表的数组)。 从DB加载表时,您应该通过订单列对其进行排序。