2015-08-14 3 views
0

Прежде всего я объясню, что я хочу сделать, и я вышлю код ниже. У меня есть служба Bluetooth, ListView с пользовательским адаптером и обработчик для службы bluetooth, который будет уведомлять, подключен ли телефон || Подключение || Disconected формирует устройство BT.Android ListView неправильный Обновление элемента

В моем списке ListView есть устройства Bluetooth поблизости, например, щелчок на элементе, например, обновлен, и телефон подключится к этому устройству.

Предположим, у меня есть 2 устройства BT. Если я выберет первый, будет обновляться метка первого (это верно), НО, если я выберу пункт №. 2, по какой-то причине это обновление также первый Lable < - ЭТО ПРОБЛЕМА

Я использую фрагменты в моем приложении, код для ListViewAdapter и способ для обновления ниже:

LIST VIEW ADAPTER КОД:

public class BluetoothListViewAdapter extends ArrayAdapter<HashMap<String, String>>{ 

    Context ctx; 
    private Activity activity; 
    private ArrayList<HashMap<String, String>> data; 
    private LayoutInflater inflater = null; 
    CircularProgressButton Device = null; 

    public BluetoothListViewAdapter(Activity a, ArrayList<HashMap<String, String>> d) { 
     super(a,R.layout.template_bluetooth_listview_element,d); 

     ctx = a.getBaseContext(); 
     activity = a; 
     data = d; 
     inflater = (LayoutInflater) a.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 



    @Override 
    public long getItemId(int position) { 
     return position; 
    } 


    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     String TAG; 
     String MAC; 

     View vi = convertView; 

     if (vi == null) 
      vi = inflater.inflate(R.layout.template_bluetooth_listview_element, null); 

     Device = null; 
     Device = (CircularProgressButton) vi.findViewById(R.id.CircularProgressButton_BluetoothListElement); 



     HashMap<String, String> category = new HashMap<String, String>(); 
     category = data.get(position); 

     TAG = (category.get("TAG")); 
     MAC = (category.get("MAC")); 

     Device.setText(TAG + "\n" + MAC); 
     Device.setIdleText(TAG + "\n" + MAC); 

     if(GlobalActivity.CurrentDeviceTAG.equals(TAG) && GlobalActivity.CurrentDeviceMAC.equals(MAC) && position == GlobalActivity.CurrentDevicePosition) { // if the selected device is the one i am connected 

      if (GlobalActivity.BluetoothConnectionStatus == GlobalActivity.STATE_CONNECTED) { 
       Device.setIndeterminateProgressMode(false); 
       Device.setProgress(100); // -- update GUI Element 
      } 

      if (GlobalActivity.BluetoothConnectionStatus == GlobalActivity.STATE_NONE) { 
       Device.setIndeterminateProgressMode(false); 
       Device.setProgress(0); // -- update GUI Element 
      } 

     } 

     return vi; 
    } 

} 

BLUETOOTH ФРАГМЕНТ КОДА (позиция была сохранена на связи попробовать в статическом междунар общественности):

public void BluetoothStateChanged(int position){ 
     Adapter.getView(position, null, null); 
     Adapter.notifyDataSetChanged(); 
     BluetoothDeviceListView.setAdapter(Adapter); 


    } 

Вышеуказанный метод вызывается обработчиком службы Bluetooth при изменении состояния - это одно обновление - элемент GUI.

Извините за мой плохой английский и объяснения. У меня 27H без сна.

Мне действительно нужно исправить это.

Спасибо за ваше время

UPDATE ON REQUEST - ListView ПУНКТ РАСПОЛОЖЕНИЯ:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#424242"> 

    <com.dd.CircularProgressButton 
     android:id="@+id/CircularProgressButton_BluetoothListElement" 
     android:layout_width="match_parent" 
     android:layout_height="70dp" 
     android:layout_marginTop="16dp" 
     android:textColor="#FFFFFF" 
     android:textSize="18sp" 
     app:cpb_cornerRadius="48dp" 
     app:cpb_iconComplete="@drawable/ic_action_accept" 
     app:cpb_iconError="@drawable/ic_action_cancel" 
     android:focusable="false" 
     android:clickable="false" /> 

</LinearLayout> 
+0

&& положение == GlobalActivity.CurrentDevicePosition. Могу ли я знать значение этого и где это управляется? – Ramesh

+0

позиция - это та, что указана при нажатии на элемент; GlobalActivity.CurrentDevicePosition является одним из текущего подключенного устройства. Так что если они равны тому, что составляет 100% элемент с графическим интерфейсом, я хочу обновить –

+0

, почему вы вызываете 'Adapter.getView' ?? – Emil

ответ

0
public void BluetoothStateChanged(){ 
     int start = BluetoothDeviceListView.getFirstVisiblePosition(); 
     for(int i = start, j = BluetoothDeviceListView.getLastVisiblePosition(); i<=j; i++) { 
      View view = BluetoothDeviceListView.getChildAt(i - start); 
      if ((BluetoothDeviceListView.getItemAtPosition(i)) != null) { 
       BluetoothDeviceListView.getAdapter().getView(i, view, BluetoothDeviceListView); // Tell the adapter to update this view 
      } 

     } 
    } 
1

Вам нужно создать класс с ProgressBar и всякий раз, когда вы создаете вид в GetView() набор этот класс держателя как тег.

Смотреть следующий код:

public class BluetoothListViewAdapter extends ArrayAdapter<HashMap<String, String>>{ 

    Context ctx; 
    private Activity activity; 
    private ArrayList<HashMap<String, String>> data; 
    private LayoutInflater inflater = null; 

    public BluetoothListViewAdapter(Activity a, ArrayList<HashMap<String, String>> d) { 
     super(a,R.layout.template_bluetooth_listview_element,d); 

     ctx = a.getBaseContext(); 
     activity = a; 
     data = d; 
     inflater = (LayoutInflater) a.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 



    @Override 
    public long getItemId(int position) { 
     return position; 
    } 


    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     String TAG; 
     String MAC; 

     View vi = convertView; 
     Holder holder; 
     if (vi == null) 
     { 
      vi = inflater.inflate(R.layout.template_bluetooth_listview_element, null); 
      holder.Device = (CircularProgressButton) vi.findViewById(R.id.CircularProgressButton_BluetoothListElement); 
      vi.setTag(holder); 
     } 
     else 
      holder = (Holder) vi.getTag(); 


     HashMap<String, String> category = new HashMap<String, String>(); 
     category = data.get(position); 

     TAG = (category.get("TAG")); 
     MAC = (category.get("MAC")); 

     holder.Device.setText(TAG + "\n" + MAC); 
     holder.Device.setIdleText(TAG + "\n" + MAC); 

     if(GlobalActivity.CurrentDeviceTAG.equals(TAG) && GlobalActivity.CurrentDeviceMAC.equals(MAC) && position == GlobalActivity.CurrentDevicePosition) { // if the selected device is the one i am connected 

      if (GlobalActivity.BluetoothConnectionStatus == GlobalActivity.STATE_CONNECTED) { 
       holder.Device.setIndeterminateProgressMode(false); 
       holder.Device.setProgress(100); // -- update GUI Element 
      } 

      if (GlobalActivity.BluetoothConnectionStatus == GlobalActivity.STATE_NONE) { 
       holder.Device.setIndeterminateProgressMode(false); 
       holder.Device.setProgress(0); // -- update GUI Element 
      } 

     } 

     return vi; 
    } 

    class Holder{ 
     CircularProgressButton Device; 
    } 
} 
+0

progressbar - это бесплатная библиотека. Это кнопка, которая по щелчку меняется на индикатор выполнения круга -> : https://android-arsenal.com/details/1/67 –

+0

Я использовал ваш код, но у меня такая же проблема –

+0

вы можете обновить ваш вопрос с использованием xml-макета, который вы используете? – chandil03

Смежные вопросы