繁体   English   中英

如何在Android中将自定义适配器添加到ListView

[英]how to add a Custom adapter to listview in android

这是我的代码,用于扫描附近的蓝牙设备,但是当我向其中添加自定义适配器时,它会抛出错误。

public class MainActivity extends Activity {
ListView listDevicesFound;
Button btnScanDevice;
BluetoothAdapter bluetoothAdapter;
int REQUEST_CODE = 1;
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnScanDevice = (Button)findViewById(R.id.scan);
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    listDevicesFound = (ListView)findViewById(R.id.list);
    listDevicesFound.setAdapter(adapter);
    CheckBlueToothState();
    btnScanDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            adapter.clear();
            if(bluetoothAdapter.startDiscovery())
            {
                Toast.makeText(getBaseContext(),"Scanning",     Toast.LENGTH_LONG).show();
            }


        }
    });

    registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));



}


@Override
protected void onDestroy() {
    super.onDestroy();unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState()
{
    if (bluetoothAdapter == null)
    {
        Toast.makeText(getBaseContext(),"Bluetooth Not Supported",Toast.LENGTH_LONG).show();

    }
    else
    {
        if (bluetoothAdapter.isEnabled())
        {
            if(bluetoothAdapter.isDiscovering())
            {
                Toast.makeText(getBaseContext(),"Bluetooth is currently in device discover process",Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getBaseContext(),"Bluetooth is Enabled",Toast.LENGTH_LONG).show();
                btnScanDevice.setEnabled(true);
            }
        }
        else
        {

            Toast.makeText(getBaseContext(), "Bluetooth is not Enabled", Toast.LENGTH_LONG).show();
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_CODE);

        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == REQUEST_CODE)
    {
        CheckBlueToothState();
    }
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            adapter.add(device.getName() + "\n" + device.getAddress());
            adapter.notifyDataSetChanged();
        }
    }};
   }

定制适配器

public class MyAdapter extends ArrayAdapter<BlueDevices>

{
   Context context;
    int resources;
      ArrayList<BlueDevices> Devices = null;

     public MyAdapter(Context context, int resource,ArrayList<BlueDevices>      Devices) {
    super(context, resource, Devices);
    this.context=context;
    this.resources=resource;
    this.Devices=Devices;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView textView = new TextView(getContext());
    BlueDevices item = getItem(position);
    textView.setTextColor(Color.BLACK);
    textView.setText(item.Name+" : "+item.Mac +"  date :"+item.getDateFormatted());
    return textView;
}
public List<BlueDevices> getAllItem() {

    List<BlueDevices> result = new ArrayList<>();
    for (int i = 0; i < getCount(); i++) {
        Log.e("fef", "getAllItem: " );
        result.add(getItem(i));
    }
    return result;
}

}

BlueDevice:

public class BlueDevices {
public String Name;
public String Mac;
public Date date;

public BlueDevices(String Name)
{
    this.Name=Name;
    this.Mac=Mac;
    this.date=date;

}
private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");

public String getDateFormatted() {
    if (date == null){
        return " no date ";
    }
    return format.format(date);
}
}

这行抛出错误adapter.add(device.getName()+“ \\ n” + device.getAddress());

您的代码中有很多问题。

 Change in Bean file BlueDevices

change constructor to take two arguments.

public BlueDevices(String Name, String Mac)
{
    this.Name=Name;
    this.Mac=Mac;
}
you no need to set data because you already created method to get data. 
change in onCreate method in activity class

In your adapter class constructor take three arguments.

MyAdapter(Context context, int resource,ArrayList<BlueDevices> Devices);

so you have context that get from getApplicationContext(), resource is your layout and Devices is arraylist of your bean class. for that you have to create one layout in your res/layout and one ArrayList with bean typecase.

        ArrayList<BlueDevices> list = new ArrayList<>();

add your all devices in to this list using.
        list.add(new BlueDevices("Device1","ASDF234SDFSADF"));
        list.add(new BlueDevices("Device2","GSDFG34SAF32DF"));

Now create object of adapter class

        MyAdapter adapter = new MyAdapter(getApplicationContext(),R.layout.list_items,list);

set this adapter to your ListView using

        listview.setAdapter(adapter);

Now create method in adapter class

        public BlueDevices getDevices(int position) {return Devices.get(position);}

Add getter method in BlueDevices

        public String getName(){
            return Name;
        }
        public String getMac(){
            return Mac;
        }

Get devices list from adapter in list onItemClickListener

        BlueDevices bean = adapter.getDevices(position);
        String name = bean.getName();
        String mac = bean.getMac();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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