android - LayoutParams 返回 null

标签 android

这是我的代码,但不知道为什么返回 null?但是我可以在这里进行空检查,但是有什么问题吗?

    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);

最佳答案

根据我的经验,你必须先将 View 添加到它的父 View ,然后才能为其设置布局参数,如下所示:

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);

关于android - LayoutParams 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17975392/

相关文章:

android - getText().toString() 在输入的内容之前添加一些数字

android - 如何从 Eclipse 中删除 'unremovable' 控制台

java - Android:传递允许 recyclerview 由特定字符串填充的变量

java - 当我尝试在 fragment 生命周期中实例化新类时出错

java - Android 资源中的图像导致内存泄漏

android - 聚焦 EditText 时如何使软键盘无效

java - 使用服务在后台使用媒体播放器是好的做法还是有必要

android - 如何解决拆分的 apk 和 bundle 的版本代码之间的冲突?

android - 为生产部署 django 应用程序的必要程序

java - AndroidFragment 中的注释