无法以编程方式添加TextView



我正在尝试添加一个文本视图,并在尝试将其添加到布局时不断获得一个nullPointer。

我的布局:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/app_header" android:layout_width="match_parent"
    android:layout_height="@dimen/headerSize" android:background="@color/iPhoneBackground">
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/grey"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

我的班级:

public class AppHeader extends RelativeLayout {
    Context mContext;
    screenName sName;
    RelativeLayout parent;

    public AppHeader(Context context, screenName sn) {
        super(context);
        mContext = context;
        sName = sn;
        parent = (RelativeLayout) findViewById(R.id.app_header);
        init();
    }
    public AppHeader(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }
    public AppHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }
    public void init(){
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        TextView title = new TextView(mContext);
        switch (sName) {
            case FAVORITER:
                title.setText(mContext.getString(R.string.favourite));
                break;
            case SOKRESA:
                title.setText(mContext.getString(R.string.search));
                break;
            case REALTID:
                // tod
                break;
            case STORNINGAR:
                // tod
                break;
            case MER:
                // tod
                break;
        }
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        title.setLayoutParams(params);
        parent.addView(title);
    }
}

Logcat在最后一行"parent.addView(title);"上给了我一个nullPointer

有人知道我做错了什么吗?

这是logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{mtr.se.reskoll/mtr.se.reskoll.SokResa}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at mtr.se.reskoll.AppHeader.init(AppHeader.java:63)
            at mtr.se.reskoll.AppHeader.<init>(AppHeader.java:24)
            at mtr.se.reskoll.SokResa.setHeader(SokResa.java:50)
            at mtr.se.reskoll.SokResa.onCreate(SokResa.java:37)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
"parent"变量仅在构造函数public AppHeader(Context context, screenName sn)中初始化。如果使用其他构造函数,parent将为null。

必须在init()方法中移动行parent = (RelativeLayout) findViewById(R.id.app_header);

试试这个:

Activity activity = (Activity) mContext;
parent = (RelativeLayout) activity.findViewById(R.id.app_header);
public AppHeader(Context context) {
        super(context);
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        parent  = (MobileAndrRelativeLayout) inflater.inflate(R.layout.yourlayout, this);
        init();
    }
    public AppHeader(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        parent  = (MobileAndrRelativeLayout) inflater.inflate(R.layout.yourlayout, this);
        init();
    }
    public AppHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
        parent  = (MobileAndrRelativeLayout) inflater.inflate(R.layout.yourlayout, this);
        init();
    }

编辑:要显示文本,这取决于您使用的构造函数,因为您只在第一个构造函数中设置文本。

我建议采用不同的方法:(我还修改了第一个构造函数)

public void SetTitle(sName)
{
      switch (sName) {
            case FAVORITER:
                title.setText(mContext.getString(R.string.favourite));
                break;
            case SOKRESA:
                title.setText(mContext.getString(R.string.search));
                break;
            case REALTID:
                // tod
                break;
            case STORNINGAR:
                // tod
                break;
            case MER:
                // tod
                break;
        }
}
public void init(){
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        TextView title = new TextView(mContext);
        // we will add this line for test, to see in the problem is that the text is not displayed or the textview itself is not visible
        title.setBackgroundColor(Color.YELLOW); 
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        title.setLayoutParams(params);
        parent.addView(title);
    }

因此,在您创建自定义视图后:

AppHeader header= new AppHeader (context);
header.SetTitle("Test");

此外,为了确保开关正常工作(也就是说,你正在发送一个实际包含在开关选项中的屏幕名称),请尝试一种简单的测试方法,而不是上面的方法:

public void SetTitle(sName)
{
  title.setText("Test Title");
}

最新更新