第一個例子演示了如何完全在代碼中構(gòu)建UI。
從Android Studio生成項目,將以下代碼剪切并粘貼到 MainActivity.java
。
package com.java2s.app; //from w w w . j a v a 2 s. c om 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("Java2s.com"); 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); } }
更多建議: