动态添加一个以活动布局布局、动态

2023-09-05 02:10:46 作者:寂

我有一个自定义视图(一个TextView的扩展),我想动态添加到我的布局(不想把它列入了main.xml中的文件)。

书上说使用findViewById()的RelativeLayout的在我的Java code,那么创建我的自定义视图的新实例来获取,然后用addView的RelativeLayout的添加新的看法。

我没有得到任何错误,但是当我点击我的按钮添加新的观点,什么都没发生(的观点并没有被添加)。我是否需要按顺序设置我的自定义视图(布局宽度,布局高度为例)的附加属性为它显示?

编辑:增加code

  //改变为ImageView的,我想这可能是比较容易看到的图像
RelativeLayout的相对=(RelativeLayout的)findViewById(R.id.rellay);
MyCustomImageView mciv =新MyCustomImageView(空);
mciv.setId(5);
的LayoutParams P =新的LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
mciv.setLayoutParams(对);
mciv.setImageResource(R.drawable.someImage);
rel.Addview(mciv);
 

解决方案

请发表您的code其中添加视图。 但是,是的,你可能会错过PARAMS的宽度和高度。尝试像

 的LayoutParams P =新的LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);
txtView.setLayoutParams(对);
 
话题I办一场活动需要多少钱

或你想要什么样的宽度和高度为。此外,在XML布局,layout_width和layout_height需要的属性。

I have a custom view (an extension of a TextView) that I want to dynamically add to my Layout (don't want to include it in the main.xml file).

The book says to fetch the RelativeLayout using findViewById() in my java code then create a new instance of my custom view, then use addView on the RelativeLayout to add the new view.

I'm not getting any errors, but when I click my button to add the new view, nothing is happening (view isn't being added). Do I need to set additional properties on my custom view (layout width, layout height for example) in order for it to be shown?

EDIT: adding code

// changed to an imageview as I thought it might be easier to see an image
RelativeLayout rel = (RelativeLayout) findViewById(R.id.rellay);
MyCustomImageView mciv = new MyCustomImageView(null);
mciv.setId(5);
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mciv.setLayoutParams(p);
mciv.setImageResource(R.drawable.someImage);
rel.Addview(mciv);

解决方案

Please post your code where you add the view. But yes, you might be missing the params for width and height. Try something like

LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);    
txtView.setLayoutParams(p);

or what you would like the width and height to be. Also in xml layout, layout_width and layout_height are required attributes.