有没有办法结合基于xml的布局和"手动"布局?F.ex:
我使用像这样的"标准"xml布局:
setContentView(R.layout.mainscreen);
Run Code Online (Sandbox Code Playgroud)
然后我想要一些更动态的内容,添加如下:
LinearLayout layout = new LinearLayout(this);
setContentView(layout);
layout.addView(new CreateItemButton(this, "Button", 1));
Run Code Online (Sandbox Code Playgroud)
我意识到我无法在上面的行中创建一个新的布局,但我可能不得不以某种方式初始化xml布局.但是 - 如果我想动态添加组件,是否可能,或者我只需要采用100%手动布局?或者是否有另一种更优雅/更正确的方式呢?
(我想要做的是根据从数据库中提取的条目创建按钮.这些按钮会在数量和文本/内容上保持警惕,因此尝试动态添加它们而不是在xml布局文件中.
您可以动态地将任何元素添加到xml布局中.您必须在xml布局中有一个容器,您将在其中添加动态元素.说空的LinearLayout,id ="container".你也可以动态地构建所有东西和setContentView(yourView); yourView在哪里是添加了其他子元素的根布局元素.
EX:
Button myButton = new Button(this);
myButton.setLayoutParams(params);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
container.addView(myButton);
Run Code Online (Sandbox Code Playgroud)
要么
LinearLayout myLayout = new LinearLayout(this);
...
container.addView(myLayout);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7859 次 |
最近记录: |