java - 为 Switch 设置 id

标签 java android layout

我有一个回收 View ,它从服务器填充数据,里面的组件是一个textView和一个Switch。服务器可以返回n条数据。当我填充数据时,如何为 Switch2 设置唯一的 id,因为稍后我需要为开关设置一个监听器,我的服务器实际上返回一个唯一的 id,但我不是这样确定如何将其设置为 Switch2,或者是否有任何替代参数可用于识别 Switch?

布局

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteY="81dp">


    <android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="1dp"
        card_view:cardUseCompatPadding="true"
        >


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Switch
                android:id="@+id/switch2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="left|center_vertical"
                android:paddingLeft="5dip"
                android:layout_marginTop="16dp"
                app:layout_constraintTop_toTopOf="parent"
                tools:layout_editor_absoluteX="254dp" />

            <TextView
                android:id="@+id/user_set_light_id"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:fontFamily="sans-serif"
                android:text="TextView"
                android:textSize="20dp"
                tools:layout_editor_absoluteX="27dp"
                tools:layout_editor_absoluteY="23dp" />
        </RelativeLayout>
    </android:android.support.v7.widget.CardView>

</android.support.constraint.ConstraintLayout>

适配器

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

    private List<populate_lights> listItems;
    private Context context;

        public populateLights_adapter(List<populate_lights> listItems, Context context) {
            this.listItems = listItems;
            this.context = context;
        }



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

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            populate_lights listItem = listItems.get(position);
            holder.lightText.setText(listItem.getLightName());
            holder.status.setChecked(listItem.getState());
        }

        @Override
        public int getItemCount() {


            return listItems.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder{

            public TextView lightText;
            public Switch status;

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

                lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
                status = (Switch) itemView.findViewById(R.id.switch2);
            }
        }

    }

java类

public class populate_lights {

    private String lightName;
    private boolean state;

    public populate_lights(String lightName, boolean state){

        this.lightName = lightName;
        this.state = state;

    }

    public String getLightName(){

        return  lightName;
    }

    public boolean getState(){

        return state;
    }
}

主要

public class lightsControl extends Fragment {
    View myView;


    public static final String URL = "serverurl.com";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private List<populate_lights> listItems;
    private Switch mySwitch;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.lightscontrol, container, false);





        recyclerView = (RecyclerView)  myView.findViewById(R.id.lightsView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        listItems = new ArrayList<>();


       loadData();


        adapter = new populateLights_adapter(listItems, myView.getContext());
        recyclerView.setAdapter(adapter);





        return myView;
    }

    private void loadData(){

        final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
        progressDialog.setMessage("Loading");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
                        mySnackbar.show();

                        Log.v("DATA_RESPONSE", response);

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("lightData");

                            for(int i=0;i<array.length();i++){

                                JSONObject obj = array.getJSONObject(i);
                                Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
                                Log.v("Value ", "index=" + obj.getBoolean("Value"));

                                populate_lights popLights = new populate_lights(
                                        obj.getString("LightID"),  //unique id
                                        obj.getBoolean("Value")   //value returns true, or false
                                );
                                listItems.add(popLights);

                            }

                            adapter = new populateLights_adapter(listItems, myView.getContext());
                            recyclerView.setAdapter(adapter);

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

                        }

                    }},
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
                        mySnackbar.show();
                        Log.v("LoginFormERROR", "index=" + error);
                        progressDialog.dismiss();

                    }
                 }
        )
        };


        RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
        requestQueue.add(stringRequest);


    }

    public void showErrorAlert(){

        AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
        builder1.setMessage("Opps, something went wring");
        builder1.setCancelable(true);

        builder1.setPositiveButton(
                "Main Menu",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        getActivity().onBackPressed();
                    }
                });



        AlertDialog alert11 = builder1.create();
        alert11.show();



    }




}

屏幕截图

enter image description here

最佳答案

查看此代码是否在日志中打印正确的位置。将其放入适配器类中 View 持有者的构造函数中:

status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Log.d("Position: ", String.valueOf(getLayoutPosition()));
            }
        });

关于java - 为 Switch 设置 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183552/

相关文章:

java - Jackson JSON序列化,通过级别定义避免递归

java - 比较方法违反了它的一般契约!在java中对图像轮廓进行排序时

Javafx 使用日期选择器

Android facebook lib冲突,如何排除冲突?

java - 如何通过消息和生成的Mac计算 key

android - Android 中的 Google Plus 封面照片

Android 应用程序通过电子邮件发送图像

html - 如何将一个背景图像用于一个主 div,它有两个 div,一个在左边,一个在右边

java - Roguelike 开发 - jlabel 之上的 jlabel

wpf - System.Windows.Visibility 折叠与隐藏