Android:从代码中向特定布局添加视图 [英] Android: Add a view to a specific Layout from code

查看:19
本文介绍了Android:从代码中向特定布局添加视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些视图动态添加到已在 XML 中定义的 LinearLayout.

I want to dynamically add some views to a LinearLayout that is already defined in XML.

我可以向屏幕添加视图,但它们没有被放置在右侧 LinearLayout 的内部".

I'm able to add views to the screen but they are not being placed 'inside' the right LinearLayout.

如何从代码中获取对这个特定布局的引用,类似于使用 findViewById() 获取View?

How can I get a reference to this specific Layout from code, similar to getting a View by using findViewById()?

推荐答案

正如 Marcarse 指出的,你可以这样做

As Marcarse pointed out you can do

ViewGroup layout = (ViewGroup) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);

LinearLayout 类扩展了 ViewGroup,它本身扩展了 View 类.这使得获取对布局的引用就像获取对另一个视图的引用一样容易.

The LinearLayout class extends ViewGroup which itself extends the View class. This makes acquiring a reference to a layout as easy as getting a reference to another View.

这篇关于Android:从代码中向特定布局添加视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆