1

所以我正在尝试在 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>
...

下面是我如何从我的 Activity 创建视图:

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);
...
4

1 回答 1

0

You're trying to get the child views during the view's constructor. Since they are child views, they haven't been inflated yet. Can you move this code out of the constructor, possibly into View.onAttachedToWindow()?

http://developer.android.com/reference/android/view/View.html#onAttachedToWindow()

于 2013-04-03T01:21:23.447 回答