您好我设置了CheckedTextView,但我无法使onClick事件正常运行。 我将onClick代码放在main.layout的onCreate中,但是我在第101行获得了一个nullpointer,它是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=""
/>
我的onClick事件:
CheckedTextView chkBox = (CheckedTextView) findViewById(R.id.listCheckboxview);
chkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
((CheckedTextView) v).toggle();
}
});
答案 0 :(得分:0)
我将onClick代码放在main.layout的onCreate中,但是我在第101行得到一个nullpointer,它是chkBox.setOnClickListener(new View.OnClickListener()
这意味着chkBox
为null
,这意味着Android未找到R.id.listCheckboxview
。确保您在正确的事情上致电findViewById()
(此处,您似乎是在活动上调用它,但您的问题提到ListView
)。另外,尝试清理项目(项目&gt;从Eclipse主菜单清除,或从命令行清除ant clean
),因为有时R
常量不同步。
答案 1 :(得分:0)
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>