CheckedTextView not clickable

谁都会走 提交于 2019-12-25 09:42:34

问题


Hi i setup a CheckedTextView but I can't get the onClick event functioning. I put the onClick code in the onCreate of the main.layout but I get a nullpointer at line 101, which is chkBox.setOnClickListener(new View.OnClickListener(). The Listview is created in the onPostExecute of a AsyncTask. Can someone please help?

My CheckedTextView:

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"  
         android:id="@+id/listCheckboxview"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_weight="1" android:gravity="left"  
         android:textColor="#0075AB"  android:textStyle="bold"  android:textSize="14dip" 
         android:checkMark="?android:attr/listChoiceIndicatorMultiple"   
         android:clickable="true" 
         android:focusable="true" 
         android:text=""  
         /> 

My onClick event:

CheckedTextView chkBox = (CheckedTextView) findViewById(R.id.listCheckboxview); 
        chkBox.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) 
        { 
            ((CheckedTextView) v).toggle(); 
        } 
    });

回答1:


I put the onClick code in the onCreate of the main.layout but i get a nullpointer at line 101, which is chkBox.setOnClickListener(new View.OnClickListener()

This means that chkBox is null, which means that Android is not finding R.id.listCheckboxview. Make sure you are calling findViewById() on the right thing (here, you appear to be calling it on the activity, but your question mentions a ListView). Also, try cleaning your project (Project > Clean from the Eclipse main menu, or ant clean from the command line), as sometimes the R constants get out of sync.




回答2:


You can use a ToggleButton with a null background and a null button. ToggleButton component has another interesting feature that is setting a text to its On state and another one to its Off state. In the example bellow I've also included a selector to the text color.

<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@null"
    android:background="@null"
    android:paddingLeft="10dp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@drawable/toggle_text"
    android:textOn="My on state"
    android:textOff="My off state" />

toggle_text.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:color="@color/app_color" />

    <item
        android:color="@android:color/darker_gray" />

</selector>


来源:https://stackoverflow.com/questions/8002473/checkedtextview-not-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!