Android 动态添加视图到活动布局

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3515759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:34:54  来源:igfitidea点击:

dynamically adding a view to activity layout

androiduser-interfacetextviewrelativelayout

提问by Blair Jones

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

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

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.

这本书说在我的java代码中使用findViewById()获取RelativeLayout,然后创建我的自定义视图的新实例,然后在RelativeLayout上使用addView来添加新视图。

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

采纳答案by Mathias Conradt

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.

或者你想要的宽度和高度是什么。同样在 xml 布局中,layout_width 和 layout_height 是必需的属性。