2013-07-03 58 views
0

我有一个单一的TextView的XML布局静态和动态布局可能吗?

现在我想添加50个按钮,我想在我的java文件中动态添加!

是否可以通过java代码将属性添加到XML文件? 或者一次活动可以同时有2个布局?

用于例如,

public class Options extends Activity 
{ 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.options); 
    Button but=new Button(this); 
    but.setText("Wassup"); 
    // How do I add this button to the layout ? 
} 

} 
+0

看到这个... http:// stackoverflow。com/questions/5631913/add-a-button-dynamic-to-a-linelayout-in-android 可能是重复的。 –

回答

3

是否可以通过java代码将属性添加到XML文件?

没有,但您可以根据与setText()做添加属性ViewsLayouts。编译后,resource文件本身无法更改。

或者一个活动一次可以有2个布局吗?

简单的答案是否定的,但你可以inflate另一个布局,并将其添加到当前布局。

你可以做添加Button

充气根layoutaddView()添加Buttons什么变化例。像

Layoutinflater inflater = (LayoutInflater) getSystemService 
    (Context.LAYOUT_INFLATER_SERVICE); 
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout_file); 
Button but=new Button(this); 
but.setText("Wassup"); 
// How do I add this button to the layout ? 
ll.addView(but); 

LayoutInflater

或者,如果你想它在当前文件添加到layout你可以使用findViewById()和使用上addView()东西添加到Buttons

+0

非常感谢:) – Vaido

+0

非常欢迎 – codeMagic

0

是的,它是可能的。 setContentView(R.layout.options);findViewById()后得到你的按钮容器。你将有一个LinearLayout,RelativeLayout或其他的参考。之后,使用布局充气器和编程方式,您可以添加其他布局或组件。

希望它能帮助!

+0

我会建议你也许给他一个编码的例子。 – yams

+0

@MarkBasler我在我的个人资料中写道:我不给鱼,我很想教一个小小的捕鱼。我知道这会是一个好消息,但用他的大脑和谷歌。 OFc,如果他是支付我会写代码:) – 2013-07-03 16:44:56

+0

注意接受的答案有一个例子。它并不需要完全符合他们的需求。 – yams

0

只需使用layout.addView()式布局是通过调用findViewById(R.id.layoutId)得到的ViewGroup

1

考虑到你有如下一个XML布局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@id/mainlayout" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" > 
</TextView> 

</LinearLayout> 

在setContentView(R.layout.options)之后的Java代码;您可以执行以下操作:

LinearLayout linearLayout=(LinearLayout)findViewById(R.id.mainlayout); 
Button button=new Button(this); 
linearLayout.addView(button); 

现在,您可以在线性布局中添加尽可能多的按钮,如上所示。