我有一个android xml布局main.xml。我想在运行时为此布局添加控件(我想添加一系列包含按钮控件的其他线性布局)。我可以这样做吗?如果是,如何?如何在运行时将按钮控件添加到android xml视图?
感谢
我有一个android xml布局main.xml。我想在运行时为此布局添加控件(我想添加一系列包含按钮控件的其他线性布局)。我可以这样做吗?如果是,如何?如何在运行时将按钮控件添加到android xml视图?
感谢
我看到错误乌尔在这里做
LinearLayout mainLayout = (LinearLayout) findViewById(R.layout.main);
你[R取布局的LinearLayout对象,你应该采取的LinearLayout ID
尝试这
LinearLayout lnr = (LinearLayout) findViewById(R.id.LinearLayout01);
Button b1 = new Button(this);
b1.setText("Btn");
lnr.addView(b1);
你可以在你的代码编程,如果你想添加控件,或与查看和吹气甚至是另一个XML。
在这里,你可以阅读的基本知识:http://developer.android.com/guide/topics/ui/declaring-layout.html
我已经阅读文档,但它并没有提到如何添加新的控件(在运行时创建的),以现有的XML布局文件。 – user501223 2011-02-07 19:34:52
你可以做到这一点很容易s在要添加视图的布局上设置一个ID。说你的main.xml这个样子:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/label"
android:layout_width="fill_parent"/>
<LinearLayout android:id="@+id/container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
</LinearLayout>
让我们假设你想用的ID id/container
添加到LinearLayout
补充意见。在你onCreate
方法,你可以检索该对象以备以后使用:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContainer = (ViewGroup)view.findViewById(R.id.container);
}
现在,你都设置为其他视图添加到您的容器ViewGroup
:
LinearLayout theButtons = getButtons()
mContainer.addView(theButtons);
在getButtons
方法,你需要创建包含您需要的按钮的LinearLayout
。您可以通过编程或通过膨胀XML文件中定义的视图来完成此操作。见LayoutInflater.inflate
。
好吧,我已经得到它的工作。
的步骤如下: 首先膨胀XML布局,即
View view = View.inflate(this, R.layout.main, null);
然后实例从XML布局的容器对象插入的ViewGroup类,即
ViewGroup container = (ViewGroup) view.findViewById(R.id.myContainer);
然后创建linearLayout对象,创建并添加所需的任何控件,将linearLayout添加到容器对象并在视图对象上使用setContentView,即
container.addView(buttonsLayout);
this.setContentView(view);
只是试试这个:
LinearLayout mainLinearLayout = (LinearLayout) findViewById(R.layout.llmain);
现在动态这样
Button btn1 = new Button(this);
btn1.setText=("Button 1");
mainLinearLayout .addView(btn1);
创建按钮,现在如果你想添加onether的LinearLayout然后将其添加下面的按钮,然后
LinearLayout llinner = new LinearLayout(this);
Button btn2 = new Button(this);
btn2.setText=("Button 2");
mainLinearLayout .addView(btn2);
llinner.addView(btn2);
mainLinearLayout .addView(llinner);
试试这个:
LinearLayout ll =(LinearLayout)findViewById(R.id.linlay);
Button b = new Button(this);
b.setText("Hello");
l.addView(b);
这可以帮助你
是的,但按钮没有在xml中定义。我想要做到以下几点:Button b = new Button(this); LinearLayout mainLayout =(LinearLayout)findViewById(R.layout.main); mainLayout.addView(b),我尝试这个,但我得到一个错误。这是做到这一点的方式吗? – user501223 2011-02-07 19:31:18
什么是错误?你尝试过addView(b,新的LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT))吗? – gngr44 2011-02-07 20:54:37