Pergunta

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(); 
        } 
    });
Foi útil?

Solução

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.

Outras dicas

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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top