繁体   English   中英

从AlertDialog重新加载ListView

[英]Reloading ListView from an AlertDialog

如何从AlertDialog内部重新加载ListView? 此AlertDialog由ContectMenu生成。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    registerForContextMenu(getListView());
    ......
    MatrixCursor cursor;
    cursor = NameManager.getnameList();
    ........
    final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.row, cursor, from, to);
    setListAdapter(adapter);
}
.......
.......
case R.id.delete:
            new AlertDialog.Builder(this)
            .setTitle("Delete " + cursor.getString(1))
            .setMessage("Are you sure?")
            .setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(
                        DialogInterface dialogInterface, int i) {
                    try {
                        .......
                        // TODO reload listview

                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                }
            }).setNeutralButton("Cancel", null)
            .create().show();
            return true;

您可以调用列表视图的适配器的notifyDataSetChanged()或notifyDataSetInvalidated()

由于我还有其他8个AlertDialog需要刷新ListView ,因此我想出了一个更好的解决方案,可以在一定程度上减小代码的大小。 我创建了一个新方法refreshListView() ,每次我想刷新ListView时都会调用该方法。

......
......
public void onClick(
        DialogInterface dialogInterface, int i) {
    try {
        Runtime.getRuntime()
        .exec("/system/xbin/rm -rf "
                + selectedfolder
                .getAbsolutePath()
                .toString());
        refreshListView();

    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}
......
......
protected void refreshListView() {
    fsitem = NameManager.getfsiList();
    NameManager.WriteName(fsitem);
    MatrixCursor cursor = NameManager.getnameList();
    ListView list = (ListView) getListView();
    String[] from = { "name", "info", "status", "path", "folder", BaseColumns._ID };
    int[] to = { R.id.name, R.id.info, R.id.status, R.id.path };
    final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.row, cursor, from, to);
    list.setAdapter(adapter);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM