Android UI 代码
下面的第一个例子演示了如何完全在代码中构建UI。
例子
从Android Studio生成一个项目,剪切并粘贴以下代码到MainActivity.java
。
package cn.w3cschool.app; //from www.w3cschool.cn import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout nameContainer = new LinearLayout(this); LinearLayout addressContainer = new LinearLayout(this); LinearLayout parentContainer = new LinearLayout(this); nameContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); nameContainer.setOrientation(LinearLayout.HORIZONTAL); TextView nameLbl = new TextView(this); nameLbl.setText("Name: "); TextView nameValue = new TextView(this); nameValue.setText("w3cschool.cn"); nameContainer.addView(nameLbl); nameContainer.addView(nameValue); addressContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); addressContainer.setOrientation(LinearLayout.VERTICAL); TextView addrLbl = new TextView(this); addrLbl.setText("Address:"); TextView addrValue = new TextView(this); addrValue.setText("Main Street"); addressContainer.addView(addrLbl); addressContainer.addView(addrValue); parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); parentContainer.setOrientation(LinearLayout.VERTICAL); parentContainer.addView(nameContainer); parentContainer.addView(addressContainer); setContentView(parentContainer); } }