所以我正在尝试在Android中实现MVC模式,其中我的视图是从RelativeLayout,LinearLayout,ScrollView等子类化的......它一直工作,直到我试图在我的视图中保持视图。我得到了NPE。我已经尝试访问视图,以便在构造函数和onAttachedToWindow()中设置onClickListener,但我在两个地方都获得了NPE。
例如,这是一个视图类:
public class ViewAchievements extends LinearLayout
{
private RelativeLayout mRelativeLayoutAchievement1;
public ViewAchievements(Context context, AttributeSet attrs)
{
super(context, attrs);
mRelativeLayoutAchievement1 = (RelativeLayout) findViewById(R.id.relativeLayout_achievement1);
mRelativeLayoutAchievement1.setOnClickListener((OnClickListener) context); //NPE on this line
}
@Override
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
mRelativeLayoutAchievement1.setOnClickListener(mOnClickListener); //Also get NPE on this line
}
}
有人可以告诉我抓住我的子视图的正确方法,在这种情况下是mRelativeLayoutAchievement1吗?
这是一个XML片段:
<com.beachbody.p90x.achievements.ViewAchievements xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/gray_very_dark"
android:orientation="vertical" >
<!-- kv Row 1 -->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:baselineAligned="false">
<RelativeLayout
android:id="@+id/relativeLayout_achievement1"
style="@style/linearLayout_achievement"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_margin="@dimen/margin_sm"
android:layout_weight="1" >
<TextView
android:id="@+id/textView_achievement1"
style="@style/text_small_bold_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="@dimen/margin_large"
android:text="1/20" />
</RelativeLayout>
...
以下是我从我的活动中创建视图的方式:
public class ActivityAchievements extends ActivitySlidingMenu
{
private ViewAchievements mViewAchievements;
@Override
public void onCreate(Bundle savedInstanceState)
{
mViewAchievements = (ViewAchievements) View.inflate(this, R.layout.view_achievements, null);
setContentView(mViewAchievements);
...
答案 0 :(得分:0)
您正在尝试在视图的构造函数中获取子视图。由于他们是儿童观点,他们还没有被夸大。你可以将这段代码移出构造函数,可能会移到View.onAttachedToWindow()中吗?
http://developer.android.com/reference/android/view/View.html#onAttachedToWindow()