MainActivity.java
package com.example.addview; import android.app.Activity; import android.content.Context; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout layoutMain = new LinearLayout(this); layoutMain.setOrientation(LinearLayout.VERTICAL); //設定layout為子物件排列方式為垂直 setContentView(layoutMain); //將create的layoutMain(LinearLayout)做為主要的activity setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //設定layout為顯示方式垂直 //將子頁login_title及login加入layoutMain LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); RelativeLayout layoutTitle = (RelativeLayout) inflate.inflate( R.layout.login_title, null); RelativeLayout layoutBody = (RelativeLayout) inflate.inflate( R.layout.login, null); //設定login_title及login加入layout的屬性 RelativeLayout.LayoutParams relParam = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutMain.addView(layoutTitle, relParam); layoutMain.addView(layoutBody, relParam); // 動態產生TextView TextView tv = new TextView(this); tv.setText("Hello World"); // 將 TextView 加入到login.xml中 (在login.xml中的RelativeLayout元件,需命名id名稱(rl_body) RelativeLayout rl_body= (RelativeLayout)findViewById(R.id.rl_body); rl_body.addView(tv); } }login_title.xml
login.xml
AndroidManifest.xml
沒有留言:
張貼留言