Android:以编程方式添加TextView不起作用

Android:以编程方式添加TextView不起作用,android,textview,android-relativelayout,Android,Textview,Android Relativelayout,我在尝试将TextView添加到RelativeLayout时遇到问题。我的代码是: TextView lectureView = new TextView(this); LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); //lp.setMargins(0,60,0,0); lectureView.setTe

我在尝试将
TextView
添加到
RelativeLayout
时遇到问题。我的代码是:

        TextView lectureView = new TextView(this);
        LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        //lp.setMargins(0,60,0,0);
        lectureView.setTextColor(0xffffff);
        lectureView.setBackgroundColor(0x000080);
        lectureView.setText(lect.getCourse().getName());

        ((RelativeLayout)findViewById(R.id.mondayRelativeLayout)).addView(lectureView);
        ((RelativeLayout)findViewById(R.id.mondayRelativeLayout)).invalidate();
但实际上它似乎被忽视了。没有添加
TextView
,代码被执行,因为我在这些行之前有一个日志调试语句,并且它被正确打印出来。我在日志中没有看到任何奇怪的东西。。。唯一的问题是没有显示
TextView

有人知道我的代码有什么问题吗


谢谢。

您尚未为textview设置布局参数。在将textview添加到RelativeLayout时执行此操作,如下所示

    ((RelativeLayout)findViewById(R.id.mondayRelativeLayout)).addView(lectureView,lp);

您正在使用的LayoutParams应该是RelativeLayout,如果不是,那么它们应该是RelativeLayout,并且您要在哪个函数中添加textview
LayoutParams
是android.widget.RelativeLayout.LayoutParams的。在调用
setContentView
方法之后,我已将此代码放入我的
活动的
onCreate
方法中。您的代码没有任何问题。显示RelativeLayoutXML。在两者之间,请尝试设置textSize。将0xffffff更改为
Color.WHITE
并将0x000080更改为
Color.BLACK
尝试注释最后一行添加
setTextSize
为我解决了这个问题。谢谢。多蠢的虫子啊。这实际上就是问题所在。只需添加
讲师视图.setLayoutParams(lp)让它工作。谢谢