2016-03-30 1 views
0

, так что я довольно новичок, чтобы просматривать виды в Android и Android в целом. проблема, с которой я сейчас сталкиваюсь, заключается в том, что у меня есть кнопка переключения для каждого элемента в виде списка, этот переключатель переключается на включение или выключение в зависимости от того, что он читает с сервера.как отправить данные с помощью кнопки переключения в виде списка андроида

Теперь моя проблема в том, что я не знаю, как и где начать, чтобы сделать эту кнопку переключения нажатием кнопки для каждого из элементов списка, которые затем отправляют новый статус кнопки и идентификатора устройства (идея заключается в том, чтобы включить или выключить свет)

Я отправлю свой код ниже. Если вам нужно что-нибудь еще, спросите. Я застрял на этом около недели, и это сводит меня с ума!

это моя основная деятельность, которая тянет JSONarray пунктов положить в поле зрения

package mmu.tom.linkedviewproject; 

import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.ImageButton; 
import android.widget.ListView; 

import org.json.JSONArray; 

public class MainActivity extends AppCompatActivity { 
    private static final String TAG = "ShowDevice"; 
    private ListView GetAllDevicesListView; 
    private JSONArray jsonArray; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Log.i(TAG, " OPened this"); 

     ImageButton button1 = (ImageButton) findViewById(R.id.image_button_new); 

     button1.setOnClickListener(new View.OnClickListener() { 
      Class ourClass; 

      public void onClick(View v) { 
       Intent i; 
       i = new Intent(MainActivity.this, DeviceDetailsActivity.class); 
       startActivity(i); 
      } 
     }); 
    } 

    public void setListAdapter(JSONArray jsonArray) { 
     this.jsonArray = jsonArray; 
     this.GetAllDevicesListView.setAdapter((new GetAllDeviceListViewAdapter(jsonArray, this))); 
    } 

    private class GetAllDevicesTask extends AsyncTask<ApiConnector,Long,JSONArray> { 
     @Override 
     protected JSONArray doInBackground(ApiConnector... params) { 
      // it is executed on Background thread 
      return params[0].GetAllDevicesState(); 
     } 

     @Override 
     protected void onPostExecute(JSONArray jsonArray) { 
     setListAdapter(jsonArray); 
     } 
    } 
} 

и это, где я создал и создать, как элементы будут выглядеть и, по существу, на мой взгляд список адаптер.

package mmu.tom.linkedviewproject; 

import android.app.Activity; 
import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.ToggleButton; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

/** 
* Created by Tom on 08/02/2016. 
*/ 

public class GetAllDeviceListViewAdapter extends BaseAdapter { 
    private JSONArray dataArray; 
    private Activity activity; 
    private String state; 

    private static LayoutInflater inflater = null; 

    public GetAllDeviceListViewAdapter(JSONArray jsonArray, Activity a) { 
     this.dataArray = jsonArray; 
     this.activity = a; 
     inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public int getCount() { 
     return this.dataArray.length(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return position; 
    } 

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

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // set up the convert view if it's null 
     ListCell cell; 
     if (convertView == null) { 
      convertView = inflater.inflate(R.layout.get_all_devices_list_view_cell,null); 
      cell = new ListCell(); 
      cell.deviceName = (TextView) convertView.findViewById(R.id.device_name); 
      cell.deviceId = (TextView) convertView.findViewById(R.id.device_id); 
      cell.type = (TextView) convertView.findViewById(R.id.type); 
      cell.toggleButton = (ToggleButton) convertView.findViewById(R.id.toggleButton); 
      cell.typeImg = (ImageView) convertView.findViewById(R.id.device_type); 
      convertView.setTag(cell); 
     } else { 
      cell = (ListCell) convertView.getTag(); 
     } 

     // changes the cell data here 

     try { 
      JSONObject jsonObject = this.dataArray.getJSONObject(position); 
      cell.deviceName.setText(jsonObject.getString("name")); 
      cell.deviceId.setText(" " + jsonObject.getString("deviceID")); 
      cell.type.setText(" " + jsonObject.getString("type")); 

      String toggle = jsonObject.getString("currentState"); 
      if (toggle.equals("on")) { 
       cell.toggleButton.setChecked(true); 
      } else { 
       cell.toggleButton.setChecked(false); 
      } 

      String device = jsonObject.getString("type"); 
      if (device.equals("Light")) { 
       cell.typeImg.setImageResource(R.mipmap.ic_lights_on); 
      } else if (device.equals("Lock")) { 
       cell.typeImg.setImageResource(R.mipmap.ic_lock_open_black_24dp); 
      } 
      // remember to set the image to type in future 
     } catch(JSONException e) { 
      e.printStackTrace(); 
     } 

     return convertView; 
    } 

    private class ListCell { 
     private TextView deviceName; 
     private TextView deviceId; 
     private TextView type; 
     private ImageView typeImg; 
     private ToggleButton toggleButton; 
    } 
} 

ответ

0

Насколько я понял, вы ищите это.

cell.ToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 

      if(isChecked) 
      { 
       //your action 
      } 
      else 
      { 
       //your action 
      } 
     } 
    }); 
+0

Я видел это несколько раз, но я не уверен, где он идет, я попытался поместить его в адаптер просмотра списка, но он просто бросает странные ошибки, любую идею, куда его поместить? – Tfish

+0

вам нужно установить метод getView() адаптера. Скажите мне, какие ошибки вы получаете –

+0

, какая часть извините, в инструкции if или try catch? – Tfish