按钮单击时从ListView获取getSelectedItem()

时间:2016-12-21 20:11:07

标签: android listview

我正在尝试在用户点击按钮时检索ListView的所选项目。我在setOnItemClickListener中使用以下代码:

lvequipments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Object o = lvequipments.getItemAtPosition(i);
            CustomerEquipmentView customerEquipmentView = (CustomerEquipmentView)o;
            Product product = workOrderPresenter.getCustomerModel().getProduct(customerEquipmentView);

            Toast.makeText(getBaseContext(), customerEquipmentView.getModelName(), Toast.LENGTH_LONG).show();

        }
    });

当我在ListView中选择不同的项目时,toast成功从对象获取模型名称。在ListView之外我有一个按钮,可以保存来自不同面板的一些数据。我试图在这里再次检索ListView项目

public void saveToDatabase() {
        Object o = lvequipments.getSelectedItem();
        CustomerEquipmentView customerEquipmentView = (CustomerEquipmentView)o;
        ...
}

o为空。在运行期间在断点处评估lvequipments.getSelectedItem()也给出null。如何从ListView方法外部onItemClick()成功检索所选项目?

1 个答案:

答案 0 :(得分:1)

  1. 在类中定义一个int字段,如int SelectedItemIndex
  2. 在onItemSelected(...)方法中写入SelectedItemIndex = i
  3. 在savetodatabase方法中通过lvequipments.getItemAtPosition(SelectedItemIndex)获取所选元素; 那就是你想要的我想