【问题标题】:Passing object to new activity in a clickable List View将对象传递给可点击列表视图中的新活动
【发布时间】:2017-09-01 04:46:50
【问题描述】:

我已经使用 ArrayAdaptor 实现了一个可点击的列表视图:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_tasks);

    myTasksListView = (ListView) findViewById(R.id.mytasks_listView);
    myTasksListView.setOnItemClickListener(this);
    tasks = getTasks(); //of type Task[]
    ArrayAdapter<Task> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, tasks);
    myTasksListView.setAdapter(adapter);
}

public void onItemClick(AdapterView<?> l, View v, int position, long id) {
    Intent intent = new Intent(this, TaskDetail.class);
    intent.putExtra("position", position);
    intent.putExtra("id", id);
    startActivity(intent);
}

现在,在我开始点击项目的新活动中,我可以获得被点击项目的位置;但是,我不确定获取实际数组的最佳方法是什么。我可以吗

  • 找到启动新活动的活动,然后从那里访问 ArrayAdaptor?

  • 让我的类 Task 可打包,然后在我的对象本身上调用 intent.putExtra()?

或者这是另一种被认为是“最佳实践”的方法?我试图跟随this helpful comment,但看起来有问题的数组是硬编码的?

【问题讨论】:

    标签: android listview


    【解决方案1】:

    最好的方法是让Task 类实现Parcelable 接口。如果你这样做了,你就可以使用Intent.putExtra(String, Parcelable[]) 并简单地调用

    intent.putExtra("tasks", tasks);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 2020-05-05
      • 1970-01-01
      • 2023-03-12
      • 2015-09-17
      相关资源
      最近更新 更多