切换列表视图行中 2 个按钮的按钮状态

问题描述 投票:0回答:1

我有一个显示 2 行列表视图的活动。每行都有一个问题,从数据库中提取,每行有 2 个按钮,一个“是”按钮和一个“否”按钮。

我试图在每行的每个按钮上设置用户选择的按下状态。因此,如果用户点击浅绿色“是”按钮,则它会变成深绿色以指示已选择,并且应取消选择红色“否”按钮。

发生的情况是,如果我点击第一行的“是”按钮,第 2 行的“是”按钮的状态会发生变化。

我在类中放置了一个结构来保存状态,但它无法正常工作。 有谁知道为什么这不能正常工作吗?

public class CarerRetentionQuestionsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{


    private static final String TAG = CarerRetentionQuestionsActivity.class.getSimpleName();
    NfcScannerApplication appObj;
    Cursor cursor;
    ListView listViewQuestions;

    MyAdapter myAdapter;

    LoaderManager loadermanager;
    CursorLoader cursorLoader;

    Context context;

    Cursor c;

    Button buttonYes;
    Button buttonNo;

    Button submit;

    private boolean[][] buttonStates;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_carer_retention);

        loadermanager = LoaderManager.getInstance(this);
        appObj = (NfcScannerApplication) getApplication();

        context = this;

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.beeactionbar);
        setTitle("Carer Wellbeing");


        listViewQuestions = (ListView) findViewById(R.id.listviewcarerretention);





        submit = (Button) findViewById(R.id.buttoncarerwellbeingsubmit);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "submit clicked");

                String res2 = appObj.loginValidate.haveCarerRetentionQuestionsBeenAsked();

                if (res2 != null && res2.equalsIgnoreCase("YES")) {

                    Intent i = new Intent(CarerRetentionQuestionsActivity.this, NfcscannerActivity2.class);
                    i.setAction("QRCODE_ACTION");
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);

                }


            }
        });







        Cursor anyquestionsInDB = appObj.loginValidate.queryAllFromCarerRetentionQuestions();

        if(anyquestionsInDB != null && anyquestionsInDB.getCount() == 0) {


            ContentValues cv = new ContentValues();
            cv.putNull(LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME);
            cv.put(LoginValidate.C_CARERRETENTIONQUESTIONTIME_QUESTION, "Do you feel supported in your role?");
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_TIMESTAMP);
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_ANSWER);
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_SENTTOSERVER);

            appObj.loginValidate.insertCarerRetentionQuestions(cv);

            ContentValues cv2 = new ContentValues();
            cv2.putNull(LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME);
            cv2.put(LoginValidate.C_CARERRETENTIONQUESTIONTIME_QUESTION, "Are you happy with the number of hours we are asking you to deliver?");
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_TIMESTAMP);
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_ANSWER);
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_SENTTOSERVER);

            appObj.loginValidate.insertCarerRetentionQuestions(cv2);

        }

        try{
            anyquestionsInDB.close();
        }catch(Exception e){}




        String[] from = { C_CARERRETENTIONQUESTIONTIME_QUESTION};
        int[] to = { R.id.rowcarerretentionquestion};

        myAdapter = new MyAdapter(appObj, R.layout.rowcarerretention, null, from, to, 0);
        listViewQuestions.setAdapter(myAdapter);

        loadermanager.initLoader(1, null, this);


    }//END OF onCreate



    private class MyAdapter extends SimpleCursorAdapter {



        public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
            super(context, layout, c, from, to, flags);

            buttonStates = new boolean[getCount()][2]; // Initialize button states array based on the count of items in the list
            // Initially set all buttons to not selected
            for (int i = 0; i < getCount(); i++) {
                buttonStates[i][0] = false; // Yes button
                buttonStates[i][1] = false; // No button
            }


        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.e(TAG, "inside myadapter getview");
            View v = super.getView(position, convertView, parent);
            if(v == null)
                return null;

            c = (Cursor)getItem(position);




            final String question = c.getString(c.getColumnIndexOrThrow(C_CARERRETENTIONQUESTIONTIME_QUESTION));
            ((TextView)v.findViewById(R.id.rowcarerretentionquestion)).setText( question);

            Log.e(TAG, "question is set, about to inflate yes/no buttons");

            buttonYes = (Button) v.findViewById(R.id.rowcarerretentionbuttonyes);
            buttonNo = (Button) v.findViewById(R.id.rowcarerretentionbuttonno);



            buttonYes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e(TAG, "button yes clicked");

                    // Toggle the state of the Yes button
                    buttonStates[position][0] = !buttonStates[position][0];
                    // Set the No button state to not selected
                    buttonStates[position][1] = false;
                    // Update the visual appearance of buttons
                    updateButtonState(position);

                    //----------------

                    buttonYes.setSelected(true);
                    buttonNo.setSelected(false);

                    DateTime dt = new DateTime();
                    long dtmills2 = dt.getMillis();

                    appObj.loginValidate.updateCarerRetentionQuestionsAsBeenAsked(question, "YES", dtmills2);



                }
            });


            buttonNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e(TAG, "button no clicked");

                    // Toggle the state of the No button
                    buttonStates[position][1] = !buttonStates[position][1];
                    // Set the Yes button state to not selected
                    buttonStates[position][0] = false;
                    // Update the visual appearance of buttons
                    updateButtonState(position);

                    //-------------------------

                    buttonYes.setSelected(false);
                    buttonNo.setSelected(true);

                    DateTime dt2 = new DateTime();
                    long dtmills2 = dt2.getMillis();

                    appObj.loginValidate.updateCarerRetentionQuestionsAsBeenAsked(question, "NO", dtmills2);



                }
            });


            // Update the visual appearance of buttons based on their states
            updateButtonState(position);

            return v;
        }
            }



    // Method to update the visual appearance of buttons based on their states
    private void updateButtonState(int position) {
        // Get the current view from ListView
        View view = listViewQuestions.getChildAt(position - listViewQuestions.getFirstVisiblePosition());
        if (view != null) {
            // Find the Yes and No buttons within the current view
            Button buttonYes = view.findViewById(R.id.rowcarerretentionbuttonyes);
            Button buttonNo = view.findViewById(R.id.rowcarerretentionbuttonno);

            // Update Yes button state
            if (buttonStates[position][0]) {
                // Set selected state appearance
                buttonYes.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green1));
            } else {
                // Set not selected state appearance
                buttonYes.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green4));
            }

            // Update No button state
            if (buttonStates[position][1]) {
                // Set selected state appearance
                buttonNo.setBackgroundColor(ContextCompat.getColor(mContext, R.color.red1));
            } else {
                // Set not selected state appearance
                buttonNo.setBackgroundColor(ContextCompat.getColor(mContext, R.color.red4));
            }
        }
    }




    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {


        String[] projection = { LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME, C_CARERRETENTIONQUESTIONTIME_QUESTION};


        cursorLoader = new CursorLoader(this, RR3ContentProvider.CONTENT_URI_CARERRETENTION, projection, null, null, null);
        return cursorLoader;
    }


    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {

        if(myAdapter!=null && c !=null)
            myAdapter.swapCursor(c); //swap the new cursor in.
        else
            Log.e(TAG,"OnLoadFinished: mAdapter is null");
    }


    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {

        if(myAdapter!=null)
            myAdapter.swapCursor(null);
        else
            Log.e(TAG,"OnLoadFinished: mAdapter is null");

    }





}//end of class
android listview android-button
1个回答
0
投票
//Data Model: Define a data model class to represent each item in your list view. This class should include properties to hold the state of each button (e.g., whether it's selected or not).


public class Question {
    private String questionText;
    private boolean isYesSelected;

    // Constructor, getters, and setters
}

//Create a custom adapter for your ListView. In the adapter, you'll //bind data to your list items and handle the button clicks.

//Design your list view item layout (e.g., list_item_layout.xml) to //include two buttons for each row.

// 通过扩展 BaseAdapter 或 //ArrayAdapter 来实现您的自定义适配器。重写 getView 方法来扩充列表项 //布局并将数据绑定到它。另外,为您的//按钮设置点击侦听器以更新状态。

public class CustomAdapter extends BaseAdapter {
    private List<Question> questionList;
    private Context context;

    // Constructor and other methods

    @Override
    public View getView(int position, View convertView,ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_item_layout, null);
        }

        Button yesButton = view.findViewById(R.id.yes_button);
        Button noButton = view.findViewById(R.id.no_button);

        Question question = questionList.get(position);

        // Set button states based on question object
        yesButton.setSelected(question.isYesSelected());
        noButton.setSelected(!question.isYesSelected());

        // Set click listeners for buttons
        yesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Update the state of buttons based on this button click
                question.setYesSelected(true);
                notifyDataSetChanged();
            }
        });

        // Similar implementation for noButton

        return view;
    }
}

// 处理按钮点击:在按钮的点击侦听器中, // 更新按钮的状态并调用 notificationDataSetChanged() // 刷新 ListView。

//By following these steps, you can ensure that when the "Yes" //button in row 1 is selected, the corresponding state in row 2 updates //accordingly. Adjust the implementation as per your specific //requirements and data model.
© www.soinside.com 2019 - 2024. All rights reserved.