0

嗨,我设置了 CheckedTextView,但我无法让 onClick 事件正常运行。我将 onClick 代码放在 main.layout 的 onCreate 中,但我在第 101 行得到一个空指针,即 chkBox.setOnClickListener(new View.OnClickListener()。Listview 是在 AsyncTask 的 onPostExecute 中创建的。有人可以帮忙吗?

我的 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=""  
         /> 

我的点击事件:

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

2 回答 2

0

我将 onClick 代码放在 main.layout 的 onCreate 中,但我在第 101 行得到一个空指针,即 chkBox.setOnClickListener(new View.OnClickListener()

这意味着chkBox就是null,这意味着Android没有找到R.id.listCheckboxview。确保您调用findViewById()的是正确的东西(在这里,您似乎是在活动中调用它,但您的问题提到了 a ListView)。此外,尝试清理您的项目(从 Eclipse 主菜单或ant clean命令行中的 Project > Clean),因为有时R常量会不同步。

于 2011-11-03T22:32:59.813 回答
0

您可以使用具有空背景和空按钮的ToggleButton 。ToggleButton 组件还有一个有趣的特性,就是将一个文本设置为 On 状态,将另一个文本设置为 Off 状态。在下面的示例中,我还为文本颜色添加了一个选择器。

<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" />

切换文本.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>
于 2015-10-06T08:25:34.910 回答