如何自动选择列表中的项目?

Posted

技术标签:

【中文标题】如何自动选择列表中的项目?【英文标题】:How to auto select an item in a list? 【发布时间】:2015-03-16 00:06:58 【问题描述】:

我有一个扫描低功耗蓝牙设备的应用程序。一旦检测到一个设备,它就会将其存储到一个列表中。当我在设备上单击时,我可以连接到此设备。

我想做的是选择这个特定的设备而不点击它。

处理点击的代码是:

protected void onListItemClick(ListView l, View v, int position, long id) 
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) 
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mScanning = false;
    
    startActivity(intent);

有没有办法用其他列表的功能做到这一点? (或任何其他方式?)

提前谢谢你

【问题讨论】:

你怎么知道你想连接列表中的第三个设备? 感谢您的回复。我暂时假设,列表中只有一个设备 【参考方案1】:

如果您有设备在列表中的位置,只需调用

onListItemClick(null, null, position, null);

如果您有 BluetoothDevice 的引用,请稍微更改一下您的 onListItemClick,以便分离功能:

protected void onListItemClick(ListView l, View v, int position, long id) 
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    connectToBluetoothDevice(device);


protected void connectToBluetoothDevice(BluetoothDevice device)

    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) 
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mScanning = false;
    
    startActivity(intent);

刚刚的电话:

connectToBluetoothDevice(device);

【讨论】:

【参考方案2】:

这是活动的全部代码:

public class DeviceScanActivity extends ListActivity 
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
BluetoothCrashResolver bluetoothCrashResolver;
//UUID[] uuids =  UUID.fromString("1811");


private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) 
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) 
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.main, menu);
    if (!mScanning) 
        menu.findItem(R.id.menu_stop).setVisible(false);
        menu.findItem(R.id.menu_scan).setVisible(true);
        menu.findItem(R.id.menu_refresh).setActionView(null);
     else 
        menu.findItem(R.id.menu_stop).setVisible(true);
        menu.findItem(R.id.menu_scan).setVisible(false);
        menu.findItem(R.id.menu_refresh).setActionView(
                R.layout.actionbar_indeterminate_progress);
    
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    switch (item.getItemId()) 
        case R.id.menu_scan:
            mLeDeviceListAdapter.clear();
            scanLeDevice(true);
            break;
        case R.id.menu_stop:
            scanLeDevice(false);
            break;
    
    return true;


@Override
protected void onResume() 
    super.onResume();
    bluetoothCrashResolver = new BluetoothCrashResolver(this.getApplicationContext());
    bluetoothCrashResolver.start();

    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) 
        if (!mBluetoothAdapter.isEnabled()) 
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        
    

    // Initializes list view adapter.
    mLeDeviceListAdapter = new LeDeviceListAdapter();
    setListAdapter(mLeDeviceListAdapter);
    scanLeDevice(true);


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) 
        finish();
        return;
    
    super.onActivityResult(requestCode, resultCode, data);


@Override
protected void onPause() 
    super.onPause();
    scanLeDevice(false);
    bluetoothCrashResolver.stop();
    mLeDeviceListAdapter.clear();



@Override
protected void onListItemClick(ListView l, View v, int position, long id) 
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) 
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mScanning = false;
    
    startActivity(intent);




private void scanLeDevice(final boolean enable) 
    if (enable) 
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() 
            @Override
            public void run() 
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            
        , SCAN_PERIOD);

        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
     else 
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    
    invalidateOptionsMenu();


// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter 
    private ArrayList<BluetoothDevice> mLeDevices;
    private LayoutInflater mInflator;

    public LeDeviceListAdapter() 
        super();
        mLeDevices = new ArrayList<BluetoothDevice>();
        mInflator = DeviceScanActivity.this.getLayoutInflater();
    

    public void addDevice(BluetoothDevice device) 
        if(!mLeDevices.contains(device)) 
            mLeDevices.add(device);
        
    

    public BluetoothDevice getDevice(int position) 
        return mLeDevices.get(position);
    

    public void clear() 
        mLeDevices.clear();
    

    @Override
    public int getCount() 
        return mLeDevices.size();
    

    @Override
    public Object getItem(int i) 
        return mLeDevices.get(i);
    

    @Override
    public long getItemId(int i) 
        return i;
    

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) 
        ViewHolder viewHolder;
        // General ListView optimization code.
        if (view == null) 
            view = mInflator.inflate(R.layout.listitem_device, null);
            viewHolder = new ViewHolder();
            viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
            viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
            view.setTag(viewHolder);
         else 
            viewHolder = (ViewHolder) view.getTag();
        

        BluetoothDevice device = mLeDevices.get(i);
        final String deviceName = device.getName();
       if (deviceName != null && deviceName.length() > 0)
            viewHolder.deviceName.setText(deviceName);
        else
            viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());
        
        return view;
    


// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() 

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) 
        runOnUiThread(new Runnable() 
            @Override
            public void run() 
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
                bluetoothCrashResolver.notifyScannedDevice(device, mLeScanCallback);
            
        );
    
;

static class ViewHolder 
    TextView deviceName;
    TextView deviceAddress;

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_
          android:layout_>
<TextView android:id="@+id/device_name"
        android:layout_
        android:layout_
        android:textSize="24dp"/>
<TextView android:id="@+id/device_address"
        android:layout_
        android:layout_
        android:textSize="12dp"/>
</LinearLayout>

DeviceScanActivity:

import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class DeviceScanActivity extends ListActivity 
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
BluetoothCrashResolver bluetoothCrashResolver;
private ArrayList<BluetoothDevice> mLeDevices;
//UUID[] uuids =  UUID.fromString("1811");


private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) 
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) 
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.main, menu);
    if (!mScanning) 
        menu.findItem(R.id.menu_stop).setVisible(false);
        menu.findItem(R.id.menu_scan).setVisible(true);
        menu.findItem(R.id.menu_refresh).setActionView(null);
     else 
        menu.findItem(R.id.menu_stop).setVisible(true);
        menu.findItem(R.id.menu_scan).setVisible(false);
        menu.findItem(R.id.menu_refresh).setActionView(
                R.layout.actionbar_indeterminate_progress);
    
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    switch (item.getItemId()) 
        case R.id.menu_scan:
            mLeDeviceListAdapter.clear();
            scanLeDevice(true);
            break;
        case R.id.menu_stop:
            scanLeDevice(false);
            break;
    
    return true;


@Override
protected void onResume() 
    super.onResume();
    bluetoothCrashResolver = new BluetoothCrashResolver(this.getApplicationContext());
    bluetoothCrashResolver.start();

    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) 
        if (!mBluetoothAdapter.isEnabled()) 
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        
    

    // Initializes list view adapter.
    mLeDeviceListAdapter = new LeDeviceListAdapter();
    setListAdapter(mLeDeviceListAdapter);
    scanLeDevice(true);


       if(mLeDevices.size() > 0)
        int position = 0;
        getListView().requestFocusFromTouch();
        getListView().setSelection(position);
        getListView().performItemClick(getListView().getAdapter().getView(position, null, null), position, getListView().getAdapter().getItemId(position));

    



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) 
        finish();
        return;
    
    super.onActivityResult(requestCode, resultCode, data);


@Override
protected void onPause() 
    super.onPause();
    scanLeDevice(false);
    bluetoothCrashResolver.stop();
    mLeDeviceListAdapter.clear();



@Override
protected void onListItemClick(ListView l, View v, int position, long id) 
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) 
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mScanning = false;
    
    startActivity(intent);




private void scanLeDevice(final boolean enable) 
    if (enable) 
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() 
            @Override
            public void run() 
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            
        , SCAN_PERIOD);

        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
     else 
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    
    invalidateOptionsMenu();


// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter 
    private LayoutInflater mInflator;

    public LeDeviceListAdapter() 
        super();
        mLeDevices = new ArrayList<BluetoothDevice>();
        mInflator = DeviceScanActivity.this.getLayoutInflater();
    

    public void addDevice(BluetoothDevice device) 
        if(!mLeDevices.contains(device)) 
            mLeDevices.add(device);
        
    

    public BluetoothDevice getDevice(int position) 
        return mLeDevices.get(position);
    

    public void clear() 
        mLeDevices.clear();
    

    @Override
    public int getCount() 
        return mLeDevices.size();
    

    @Override
    public Object getItem(int i) 
        return mLeDevices.get(i);
    

    @Override
    public long getItemId(int i) 
        return i;
    

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) 
        ViewHolder viewHolder;
        // General ListView optimization code.
        if (view == null) 
            view = mInflator.inflate(R.layout.listitem_device, null);
            viewHolder = new ViewHolder();
            viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
            viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
            view.setTag(viewHolder);
         else 
            viewHolder = (ViewHolder) view.getTag();
        

        BluetoothDevice device = mLeDevices.get(i);
        final String deviceName = device.getName();
       if (deviceName != null && deviceName.length() > 0)
            viewHolder.deviceName.setText(deviceName);
        else
            viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());
        
        return view;
    


// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() 

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) 
        runOnUiThread(new Runnable() 
            @Override
            public void run() 
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
                bluetoothCrashResolver.notifyScannedDevice(device, mLeScanCallback);
            
        );
    
;

static class ViewHolder 
    TextView deviceName;
    TextView deviceAddress;

【讨论】:

以上是关于如何自动选择列表中的项目?的主要内容,如果未能解决你的问题,请参考以下文章

自动选择下拉列表中的选定项目

从上到下滚动时如何自动停止对项目的列表视图取消选择?

JComboBox 自动完成

jQuery UI 自动完成:如何让 TAB 选择列表中的第一个选项?

如何在选中复选框时选择列表框中的所有项目?

如何将具有自动完成功能的文本字段限制为列表中的项目 - Oracle Apex 5