How to enable checkbox when clicking linked text view

I use CheckBox and TextView in my application (I; m using the image view between the checkbox and Textview, so I could not use CheckBox text). I want to enable / disable my checkbox if I click the corresponding TextView. Someone please help me.

+4
source share
2 answers

Just try the following:

main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First text box" android:id="@+id/tb_1" /> <CheckBox android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:id="@+id/cb_1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Second text box" android:id="@+id/tb_2" android:layout_marginTop="50dp" /> <CheckBox android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:id="@+id/cb_2" /> </LinearLayout> 

MyActivity.java

 public class MyActivity extends Activity implements View.OnClickListener { private TextView tv1; private CheckBox cb1; private TextView tv2; private CheckBox cb2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv1 = (TextView)findViewById(R.id.tb_1); tv2 = (TextView)findViewById(R.id.tb_2); cb1 = (CheckBox)findViewById(R.id.cb_1); cb2 = (CheckBox)findViewById(R.id.cb_2); tv1.setOnClickListener(this); tv2.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case (R.id.tb_1): { cb1.setChecked(!cb1.isChecked()); break; } case (R.id.tb_2): { cb2.setChecked(!cb2.isChecked()); break; } } } } 

When you click on one of the TextView , you simply set the current setChecked value for the nested CheckBox (for one or many). And that’s all you need. Hope this helps.

enter image description here

+3
source

I think this is easy. Add a click listener to the text box and check and uncheck the onClickListener ..

0
source

All Articles