public class DeviceListActivity extends Activity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
@Override
protected void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.activity_device_list, RESULT_CANCELED);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices) {
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n"
+ mDevice.getAddress());
}
} else {
String mNoDevices = "None Paired";// getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> mAdapterView, View mView,
int mPosition, long mLong) {
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = String.valueOf(mPairedDevicesArrayAdapter
.getItem(mPosition).toString());
String mDeviceAddress = mDeviceInfo
.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
device_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/title_paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#666"
android:paddingLeft="5dip"
android:text="My Text"
android:textColor="#fff"
android:visibility="gone" />
<ListView
android:id="@+id/paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="true" />
</LinearLayout>
我编写上面的代码来显示当前在线的 ListView 中的所有蓝牙设备。但是当我尝试此代码时,我得到以下异常。此代码在不使用阵列适配器的情况下工作正常
11-04 12:03:48.504: E/AndroidRuntime(8902): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView