我正在从SQLite数据库中以编程方式编写表格。
在循环中,我正在生成所需的TextViews
,并在数据超出现有屏幕时尝试将数据包装在名为descCol
的TextView
中。
以下链接提供了实现此操作的建议:Setting width to wrap_content for TextView through code
但是,当使用任何一种建议方法时,都会遇到java.lang.NullPointerException
错误。
这里是我的代码示例:
TextView descCol = new TextView(this);
descCol.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
在这种情况下,调试显示在
getLayoutParams()
行上抛出了一个java.lang.NullPointerException
。此外,我已经尝试过:
TextView descCol = new TextView(this);
ViewGroup.LayoutParams params = descCol.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
descCol.setLayoutParams(params);
在这种情况下,调试显示它在
params.height
行抛出了java.lang.NullPointerException
。调试显示,在执行
getLayoutParams()
方法后,无论哪种情况,params都等于null,显然会抛出异常。我尝试先为
descCol
(文本颜色、文本、重力等)分配其他参数,然后再执行getLayoutParams()
,但结果相同。欢迎提出如何避免
java.lang.NullPointerException
的建议。
LayoutParams
之前,或者将View
添加到ViewGroup
中,View
是没有LayoutParams
的。在你的两个代码片段中,getLayoutParams()
都返回了null。 - Mike M.