Android 應用程式的開發一般都將 UI 跟 RESOURCES 的部分抽離出來,好方便管理及設計,也因此有一些 XML 檔需要撰寫,主要都是用來描述這些資源。

 

但若要自己土法練鋼寫動態產生時要怎麼作?


 

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
///setContentView(R.layout.main); ///不使用 main.xml 資源

 

LinearLayout layout = new LinearLayout(this);
this.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setOrientation(LinearLayout.VERTICAL);
 
Button btn = new Button(this);
btn.SetText("Button");
layout.addView(btn, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

 

EditText txt = new EditText(this);
layout.addView(txt, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
 
 
 
 
相對照若用 xml 來描述的話像這樣...



 

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="HTTP://schemas.android.com/apk/res/android">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</Button>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>

 

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()