Using CheckedTextView in Android

In this blog post, I would like to show how to use CheckedTextView in Android.

CheckedTextView is an extension of normal TextView that has a checkbox along with some text. It can be useful when included in a ListView where it’s setChoiceMode has been set to something otherthan CHOICE_MODE_NONE.

1. Create a new project File -> Android Project. On activity_main.xml copy paste this code:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<CheckedTextView
android:id="@+id/checkedTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:checked="true"
android:text="CheckedTextView" />

</RelativeLayout>

Note: you need to set android:checkMark  attribute to provide a graphic or drawable or it will not show the check mark.

2. Now open your MainActivity.java and copy paste this code:


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckedTextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CheckedTextView ctv = (CheckedTextView) findViewById(R.id.checkedTextView1);
ctv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ctv.isChecked())
ctv.setChecked(false);
else
ctv.setChecked(true);

}
});
}

}

ScreenShot:

Screenshot_2014-12-02-15-28-38[1]

 

Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi

Leave a Reply

Your email address will not be published. Required fields are marked *