0

私はアンドロイド開発の初心者です。CardViewでrecycleViewがあるアプリケーションを作成しています。カードビュー内では、1 つの TextView と 1 つのスイッチ ボタンを使用しています。ボタンの値をサーバーに変更すると、そこで更新されます。

ボレー応答ごとに ViewHolder クラスを更新する方法を知りたいです。ViewHolder が nextTime に更新されない場合、値はサーバーで変更されませんが、Switch Button は側面を変更します。

MainClass.java

public class Light extends Fragment {

public static final String light_url = "http://192.168.0.7:8080/bizzonthego/Android/device_status.php";
private List<ItemList> LightList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

View v;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.light, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);


    LightList = new ArrayList<>();
    new Handler().postAtTime(new Runnable() {
        @Override
        public void run() {

            getData();

        }
    }, 1000);



    return v;
}

@Override
public void onStart() {
    super.onStart();

}

@Override
public void onResume() {
    super.onResume();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//                getData();
//
//            }
//        }, 1000);
}

private void getData()
{

 final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
    JsonArrayRequest jsonArrayRequest =new JsonArrayRequest(light_url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {


           loading.dismiss();
            parseData(response);


        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.dismiss();
                    Toast.makeText(getActivity(),"error to connect",Toast.LENGTH_SHORT).show();

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);

}
private void parseData(JSONArray array){


    for(int i = 0; i<array.length(); i++) {
        ItemList lightValue = new ItemList();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            String battery = json.getString("device");
            String status = json.getString("status");


            lightValue.setItem(battery);
            lightValue.setStatus(status);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        LightList.add(lightValue);
    }



    //Finally initializing our adapter
    adapter = new CardView(LightList,getActivity());
    adapter.notifyDataSetChanged();

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);

    }
}

ViewHolder.java

public class CardView extends RecyclerView.Adapter<CardView.ViewHolder>{

List<ItemList> items;
private Context context;
public static final String POST_SWITCH_URL = "http://192.168.0.7:8080/bizzonthego/Android/device_control.php";



public CardView(List<ItemList> item, Context context){
    super();
//        items = new ArrayList<ItemList>();
//                   ItemList item = new ItemList();
//            item.setItem(names);
//
//            items.add(item);
    this.items = item;
    this.context =context;

}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.permisies_cardview, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final ItemList list =  items.get(position);

    holder.textViewName.setText(list.getItem());
    final String device = list.getItem();

    if(list.getStatus().equals("0"))
    {
        holder.mySwitch.setChecked(false);
        holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "1";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue

                requestQueue.add(stringRequest);

            }
        });


    } else if(list.getStatus().equals("1"))
    {
        holder.mySwitch.setChecked(true);
        holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "0";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue
                requestQueue.add(stringRequest);

            }
        });


    }




}

@Override
public int getItemCount() {
    return items.size();
}

class ViewHolder extends RecyclerView.ViewHolder{

    public TextView textViewName;
    public SwitchCompat mySwitch;


    public ViewHolder(View itemView) {
        super(itemView);


        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        mySwitch = (SwitchCompat) itemView.findViewById(R.id.switchbtn);

    }
}

}
4

2 に答える 2

1

まず、onCreate メソッドでアダプターを作成し、それを保持します。

mAdapter = new CardView(getActivity());
recyclerView.setAdapter(mAdapter);

次のように、アダプタに新しいメソッドを作成してデータを更新します。

mAdapter.updateItems(...);

最後に、サービスから応答を受け取ったら、updateItems メソッドを呼び出して変更を通知するだけです。

mAdapter.notifyDataSetChanged();

お役に立てれば!

于 2016-06-09T09:37:01.303 に答える
0

リスト項目を更新するためにクリックされた項目を見つけるには、BindViewHolder 内のスイッチのタグを設定する必要があります。

**holder.mySwitch.setTag(position);**

その後、ボレー応答を取得したら、ItemListを更新します

 holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

          **final CompoundButton mySwitch=buttonView;**
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();
                           //Got success response from volley

 **int sPosition=mySwitch.getTag();
items.get(sPosition).setItem("YOUR TEXT");
notifyDataSetChanged();**


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "0";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue
                requestQueue.add(stringRequest);

            }
        });
于 2016-06-09T10:08:30.170 に答える