简体   繁体   中英

How to tell a spinner item which method should it call when loading is over?

I have this code:

List<BluetoothDevice> devices;
if (BluetoothDevice.ACTION_FOUND.equals(action)){
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if(device.getName() != null) {
                devices.add(device);
                Log.i("FOUND!", device.getName());
                devicesSpinner.setAdapter(new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, devices));
            }
        }

And in spinner list I am getting MAC address, how I can change it for name()?

Add the name to a list instead of the whole device.

final List<String> names = new ArrayList<>();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    final String name = device.getName();
    if(name != null) {
        names.add(name);
        Log.i("FOUND!", name);
        devicesSpinner.setAdapter(
            new ArrayAdapter<String>(context, 
               android.R.layout.simple_spinner_dropdown_item, 
               names));
    }
}

The alternative solution is to implement your own adapter class that extends ArrayAdapter<BluetoothDevice> that will call getItem(position).getName()

Thank that was very helpful. What I did is:

if (BluetoothDevice.ACTION_FOUND.equals(action)){
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if(device.getName() != null) {
                devices.add(device);
                Log.i("FOUND!", device.getName());
                ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, devices){
                    @Nullable
                    @Override
                    public Object getItem(int position) {
                        return devices.get(position).getName();
                    }
                };
                devicesSpinner.setAdapter(arrayAdapter);

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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