我有一个ListFragment,我想在列表视图中单击时编辑项目。

我正在使用这种方法。

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        if(dbHelper != null){
            Item item = dbHelper.getProjectRowById(id);
            Intent intent = new Intent(getActivity(), Save.class);
            //Here i want to start the activity and set the data using item.
        }
    }


我如何在上述方法中设置数据。

提前致谢

最佳答案

当您开始新的活动时,您可以发送其他数据以及一个Intent。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    if(dbHelper != null){
        Item item = dbHelper.getProjectRowById(id);

        // Put the data on your intent.
        Intent intent = new Intent(getActivity(), Save.class);
        // If Item implements Serializable or Parcelable, you can just send the item:
        intent.putExtra("dataToEdit", item);
        // Otherwise, send the relevant bit:
        intent.putExtra("data1", item.getSomeDataItem());
        intent.putExtra("data2", item.getAnotherDataItem());
        // Or, send the id and look up the item to edit in the other activity.
        intent.putExtra("id", id);

        // Start your edit activity with the intent.
        getActivity().startActivity(intent);
    }
}


在编辑活动中,您可以获取启动它的Intent。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(...);

    Intent intent = getIntent();
    if (intent.hasExtra("dataToEdit")) {
        Item item = (Item) intent.getSerializableExtra("dataToEdit");
        if (item != null) {
            // find edittext, and set text to the data that needs editing
        }
    }

}


然后,用户可以编辑该文本,然后可以在单击“保存”或任何其他内容时将其保存到数据库中。然后在保存活动中调用finish

如果需要将保存的数据发送回原始活动(而不是仅在onStart中重新查询),请查看startActivityForResult。如果使用它,则可以在调用setResult之前使用finish设置结果代码。

关于android - 从一个 Activity 到另一个 Activity 设置数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14410706/

10-11 22:22
查看更多