Android:以编程方式添加TextView无法正常工作

时间:2015-03-14 11:16:52

标签: android textview 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.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没有显示。

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

感谢。

1 个答案:

答案 0 :(得分:1)

您尚未为textview设置布局参数。将textview添加到RelativeLayout时这样做

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