自定义ToggleButton findViewById空指针

时间:2013-09-19 02:31:39

标签: view nullpointerexception togglebutton

我一直试图解决这个问题几个小时,并已经用尽所有明显的解决方案。我有一个自定义切换按钮,只要我不尝试使用findViewById

就可以正常工作

以下是相关代码:

public class WeekButton extends ToggleButton {

    private static int mWidth;

    public WeekButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WeekButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    ...
}

这是布局..

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="5dp">

    <org.myname.projetname.reminders.WeekButton.WeekButton
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mondayToggleButton"
        style="@style/RecurrenceDayOfWeekStyle"
        android:textOff="  Mon"
        android:textOn="  Mon" />
</LinearLayout>

此处发生异常..

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_reminder_activity);
        //This causes null pointer
        WeekButton weekButton = (WeekButton)findViewById(R.id.mondayToggleButton));
}

感谢您提供的任何帮助!

解决方案:结果我忘了实例化我添加WeekButtons的列表,这使得它看起来像找到id的调用工作但它确实有效。谢谢大家,你试图提供帮助。

2 个答案:

答案 0 :(得分:0)

运行前没有显示任何错误?为父标记提供了xml名称空间属性。

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="5dp">

<org.myname.projetname.reminders.WeekButton.WeekButton
    android:id="@+id/mondayToggleButton"
    style="@style/RecurrenceDayOfWeekStyle"
    android:textOff="  Mon"
    android:textOn="  Mon" />
</LinearLayout>

另外,在findViewById()上投放到您的班级。

答案 1 :(得分:0)

忘记实例化我正在添加周按钮的列表。

相关问题