你如何定义一个页面programmaticaly的一部分 [英] How do you declare part of a page programmaticaly

查看:178
本文介绍了你如何定义一个页面programmaticaly的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有它的布局由XML code指定的页面,但我想可能创建几个单选按钮,也就是说,在中间,但决定在运行时,我将如何做呢?我是新来的Andr​​oid,所以我采取一个在黑暗中刺伤。请问像这样的工作?

在XML中,一个的LinearLayout添加到页面的XML像这样的中间:

 <的LinearLayout机器人:ID =@ + ID / LinLayBut
机器人:方向=横向
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT/>

然后在Java是这样的:

 公共无效setupRadioButtons(){
    的LinearLayout linLay;
    linLay =(的LinearLayout)findViewById(R.id.LinLayBut);
    RadioGroup中radGroup =新RadioGroup中(本);
    单选radBut =新的单选按钮(本);
    radGroup.addView(radBut,0);
    radGroup.setText(A键);}


解决方案

这是不是建立动态UI的有效途径。你会过得更好在一个XML文件中定义可选的布局,然后当你想用它它充气:

公共无效setupRadioButtons(){
    最后LayoutInflater气筒=
        (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);    的LinearLayout按钮=
        (LinearLayout中)inflater.inflate(R.layout.LinLayBut,NULL);    的LinearLayout mainLayout =(的LinearLayout)findViewById(R.id.main);
    mainLayout.addView(按钮);
}

以上code假定无线电集团和按钮中的的LinearLayout 定义ID为 LinLayBut 你主要布局id是

If I have a page whose layout is designated by XML code, but I want to possibly create a few radio buttons, say, in the middle, but decide that at runtime, how would I do it? I'm new to Android so I'm taking a stab in the dark. Would something like this work?

In the XML, add a LinearLayout to the middle of the page's XML like this:

<LinearLayout android:id="@+id/LinLayBut"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

And then in the java something like this:

public void setupRadioButtons(){
    LinearLayout linLay;
    linLay = (LinearLayout) findViewById(R.id.LinLayBut);
    RadioGroup radGroup = new RadioGroup(this);
    RadioButton radBut = new RadioButton(this);
    radGroup.addView(radBut, 0);
    radGroup.setText("A button");

}

解决方案

This is not an efficient way to build dynamic UI. You would be better off defining the optional layout in an XML file and then inflate it when you want to use it:

public void setupRadioButtons() {
    final LayoutInflater inflater =
        (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    LinearLayout buttons =
        (LinearLayout) inflater.inflate(R.layout.LinLayBut, null);

    LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main);
    mainLayout.addView(buttons);
}

The above code assumes that the radio group and buttons are defined inside the LinearLayout with id LinLayBut and you main layout id is main.

这篇关于你如何定义一个页面programmaticaly的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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