Android: Add a view to a specific Layout from code

2019-01-23 23:50发布

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

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

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

3条回答
forever°为你锁心
2楼-- · 2019-01-24 00:22

Better Version: To add another layout in activity/Fragment

LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);

Happy Coding(-:

查看更多
趁早两清
3楼-- · 2019-01-24 00:28

This should work:

LinearLayout layout = (LinearLayout) 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);
查看更多
相关推荐>>
4楼-- · 2019-01-24 00:33

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

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.

查看更多
登录 后发表回答