Android 动态设置文本视图的宽度和高度

Android 动态设置文本视图的宽度和高度,android,dynamic,textview,Android,Dynamic,Textview,如何动态设置textview的宽度和高度 我已经试过了 displaytext.setLayoutParams(new LinearLayout.LayoutParams(rlwidth-(rlwidth*5/100),rlheight-(rlheight*90/100))); 我收到了这个错误 Java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.wid

如何动态设置textview的宽度和高度 我已经试过了

displaytext.setLayoutParams(new LinearLayout.LayoutParams(rlwidth-(rlwidth*5/100),rlheight-(rlheight*90/100)));
我收到了这个错误

Java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
试试这个-

displaytext.setLayoutParams(new RelativeLayout.LayoutParams(rlwidth-(rlwidth*5/100),rlheight-(rlheight*90/100)));
根据错误日志,您的
TextView
父视图看起来像
RelativeLayout

您动态设置高度和宽度的“显示文本”似乎是RelativeLayout类型,您试图转换为linearlayout

txtview = (TextView)findViewById(R.id.txtview); txtview.setTextColor(Color.parseColor("#53565a")); ViewGroup.MarginLayoutParams layoutParams_txtview =(ViewGroup.MarginLayoutParams) .getLayoutParams(); layoutParams_txtview.topMargin = 8*y/100; txtview.setLayoutParams(layoutParams_txtview); txtview.getLayoutParams().height = 4*y/100; txtview.getLayoutParams().width = 30 * x / 100; txtview.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); txtview.setTypeface(typeface_regular); txtview=(TextView)findViewById(R.id.txtview); setxtcolor(Color.parseColor(“#53565a”); ViewGroup.MarginLayoutParams layoutParams_txtview=(ViewGroup.MarginLayoutParams.getLayoutParams(); layoutParams_txtview.topMargin=8*y/100; setLayoutParams(layoutParams\u txtview); txtview.getLayoutParams().height=4*y/100; txtview.getLayoutParams().width=30*x/100; txtview.setGravity(重力.重心垂直|重力.重心水平); txtview.setTypeface(常规字体);
您可以使用代码并根据自己的要求进行修改。

谢谢您的支持,我已经得到了答案。为文本视图设置尺寸实际上更容易。这是我使用的代码

displaytext.setWidth(rlwidth);
   displaytext.setHeight(rlheight*16/100);
   displaytext.setTextSize(rlheight*6/100);

现在它工作得很好。

将LinearLayout.LayoutParams更改为RelativeLayout.LayoutParams。它会起作用的。因为你的文本视图在RelativeLayout中。我试过了,但仍然不起作用