首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回null的LayoutParams

返回null的LayoutParams
EN

Stack Overflow用户
提问于 2013-08-01 00:04:56
回答 2查看 3.6K关注 0票数 2

这是我的代码,但是不知道为什么它返回null?然而,我可以在这里放一个空检查,但是有什么问题吗?

代码语言:javascript
复制
    TextView descriptiontv = (TextView) findViewById(R.id.descriptiontv);
    TextView tc = new TextView(c);
    final PopupWindow windowPopUp = new PopupWindow(tc,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT ,false);

    tc.setBackgroundResource(R.drawable.bg_training_baloon_hc_2x);
    tc.setText("this is a demo test to check how it looks, i m just wanting to test whether it works or not");
    tc.setPadding(20, 20, 20, 20);
    LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    params.setMargins(30, 0, 30, 0);
    tc.setLayoutParams(params);
EN

回答 2

Stack Overflow用户

发布于 2015-06-06 17:49:59

根据我的经验,在为视图设置布局参数之前,必须先将视图添加到其父视图中,如下所示:

代码语言:javascript
复制
TextView calendarYear = new TextView(getActivity());
calendarYear.setText(calendar.getYear() + "");
calendarYear.setTextSize(20);
calendarYear.setTypeface(null, Typeface.BOLD);
calendarYear.setGravity(Gravity.CENTER);
calendarYear.setTextColor(resources.getColor(android.R.color.black));
calendarItemsLinearLayout.addView(calendarYear);

// We have to add the TextView to the layout first before we
// can set the layout margins for it
ViewGroup.LayoutParams layoutParams = calendarYear.getLayoutParams();
((LinearLayout.LayoutParams)layoutParams).setMargins(0, (int)(16 * density), 0, 0);
calendarYear.setLayoutParams(layoutParams);
票数 2
EN

Stack Overflow用户

发布于 2013-08-01 00:06:57

这里

代码语言:javascript
复制
tc.getLayoutParams()

您还没有给它任何params,所以它将返回null。也许你的意思是

代码语言:javascript
复制
descriptiontv.getLayoutParams()

编辑

试着改变

代码语言:javascript
复制
params.leftMargin = 30;
params.rightMargin = 30;

代码语言:javascript
复制
params.setMargins(30, 0, 30, 0);

和改变

代码语言:javascript
复制
LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams)tc.getLayoutParams();

代码语言:javascript
复制
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17975392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档