我有ListView,我想将图像添加到列表中的每个项目。我试过很多代码,但没有任何关系。
我也在使用ListActivity,这是我正在使用的代码,
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private static final String TAG = null;
public static int RSSI;
public static String NAME;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.scanning);
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;
}
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> adpter, View v, int position, long id) {
//Toast.makeText(DeviceScanActivity.this,"alaaaaaa", Toast.LENGTH_LONG).show();
openContextMenu(adpter);
return false;
}
});
registerForContextMenu(getListView());
}
final int CONTEXT_MENU_RENAME = 3;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo)
{
menu.add(Menu.NONE, CONTEXT_MENU_RENAME, Menu.NONE, "Rename");
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Long id = getListView().getAdapter().getItemId(info.position);
final int number_of_item_in_listview = Integer.valueOf(id.intValue());
// final int context_menu_number = item.getItemId();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Rename item");
alert.setMessage("Enter new name for selected item");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = input.getText().toString();
mDeviceList.set(number_of_item_in_listview, value);
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
}
});
alert.show();
return(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.details, 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();
// 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);
mLeDeviceListAdapter.clear();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
Intent in = new Intent(this, FindIT.class);
in.putExtra("name", NAME);
in.putExtra("rssi", RSSI);
startActivity(in);
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
// if (mLeDeviceListAdapter.isEmpty()) {
// MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound1);
//mp.start();
//Toast.makeText(DeviceScanActivity.this, R.string.none_found, Toast.LENGTH_LONG).show();
//}
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
getActionBar().setTitle(R.string.select_device);
if (mLeDeviceListAdapter.isEmpty()) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound1);
mp.start();
Toast.makeText(DeviceScanActivity.this, R.string.none_found, Toast.LENGTH_LONG).show();
}
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;
private final HashMap<BluetoothDevice, Integer> rssiMap = new HashMap<BluetoothDevice, Integer>();
List<HashMap<String,String>> tag1 =
new ArrayList<HashMap<String,String>>();
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device , int rssi) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
rssiMap.put(device, rssi);
}
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);
// viewHolder.deviceRssi = (TextView) view.findViewById(R.id.rssi1);
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
// Planet p = planetList.get(position);
viewHolder.deviceName.setText(R.string.unknown_device);
// viewHolder.deviceAddress.setText(device.getAddress());
// viewHolder.deviceRssi.setText(""+rssiMap.get(device)+" dBm");
RSSI= rssiMap.get(device);
NAME = device.getName();
Toast.makeText(DeviceScanActivity.this,getCount() + " Device(s)" + "found" , Toast.LENGTH_LONG).show();
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
setTitle(R.string.connectedTags);
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device, rssi);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
// TextView deviceAddress;
// TextView deviceRssi;
}
}
有人可以给我正确的代码吗?
答案 0 :(得分:0)
基本上,您需要在自定义行布局ImageView
中添加list_item_device
。
<ImageView
android:width="match_parent"
android:height="wrap_content"
android:id="@+id/imageV" />
并且,在ViewHolder
类中,在TextView下面添加ImageView,
static class ViewHolder {
TextView deviceName;
ImageView img;
}
在getView
方法中,
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceName = (TextView)view.findViewById(R.id.device_name);
viewHolder.img = (ImageView)view.findViewById(R.id.imageV);
view.setTag(viewHolder);
然后,就像您将文字设置为TextView
一样,为ImageView
执行,
viewHolder.img.setImageResource(resources should come here);
编辑:
在列表视图中显示文字和图片的示例代码 - list_item_device.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/imageV" />
</RelativeLayout>
答案 1 :(得分:0)
如果你不喜欢OutofMemory Errors,请使用图片加载器。下载https://github.com/nostra13/Android-Universal-Image-Loader并将其作为库添加到您的应用程序中。 首先,我将向您展示如何使用从SQLITE获取数据的列表 这是你的布局
<TextView
android:id="@+id/_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:visibility="gone" />
<TableRow
android:layout_width="match_parent"
android:layout_height="80dp" >
<ImageView
android:id="@+id/image"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:scaleType="fitXY"
android:textColor="#1464F4"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight=".2"
android:gravity="center"
android:hint="Cool Product"
android:textColor="#1464F4"
android:textSize="18sp"
android:textStyle="bold" />
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight=".1" >
<TextView
android:id="@+id/description"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight=".1"
android:gravity="center"
android:hint="Very nice product"
android:textColor="#1464F4"
android:textSize="10sp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="$"
android:textColor="#1464f4"
android:textSize="24sp" />
<TextView
android:id="@+id/p"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight=".1"
android:gravity="center_vertical|center_horizontal"
android:hint="0.00"
android:textColor="#1464F4"
android:textSize="22sp"
android:textStyle="bold" />
</TableRow>
</LinearLayout>
</TableRow>
这是你适应的,这里的重要部分是IMAGELOADER需要一个字符串
private static final class MyProductsAdapter extends CursorAdapter {
MyProductsAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mInflater.inflate(R.layout.view_stuff, parent, false);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView id = (TextView) view.findViewById(R.id._id);
ImageView iv = (ImageView) view.findViewById(R.id.image);
TextView n = (TextView) view.findViewById(R.id.name);
TextView m = (TextView) view.findViewById(R.id.description);
TextView s = (TextView) view.findViewById(R.id.p);
id.setText(cursor.getString(cursor.getColumnIndex("_id")));
n.setText(cursor.getString(cursor.getColumnIndex("name")));
m.setText(cursor.getString(cursor.getColumnIndex("description")));
s.setText(cursor.getString(cursor.getColumnIndex("p")));
loader.init(ImageLoaderConfiguration.createDefault(context));
loader.displayImage(cursor.getString(cursor.getColumnIndex("image")), iv, op);
}
LayoutInflater mInflater;
}
这是你的名单
final ListView list = (ListView) findViewById(android.R.id.list);
SQLiteDatabase sqLiteDatabase = controllerp.getReadableDatabase();
String query = "SELECT * FROM Whatever where name IS NOT NULL ORDER BY name COLLATE NOCASE ASC";
// rawQuery must not include a trailing ';'
final Cursor cursor = sqLiteDatabase.rawQuery(query, null);
((ListView) list).setAdapter(new MyProductsAdapter(context, cursor, 0));
如果您有任何疑问,请随时提出
答案 2 :(得分:0)
创建自定义列表适配器并为列表项创建xml布局文件。 在oreder中,如果您希望图像和文本以相同的原始方式出现,请使用LinearLayout 方向水平。 如果您仍有查询,请参阅以下教程
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/