Android 動態載入佈局檔案
阿新 • • 發佈:2019-01-02
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/DynamicText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
(2) 第二種方式,通過 LayoutInflater 來間接載入,即:setContentView(R.layout.activity_main); TextView text = (TextView)this.findViewById(R.id.DynamicText); text.setText("Hello World");
LayoutInflater mInflater = LayoutInflater.from(this); View contentView = mInflater.inflate(R.layout.activity_main,null); TextView text = (TextView)contentView.findViewById(R.id.DynamicText); text.setText("Hello World"); setContentView(contentView);
LinearLayout layout = new LinearLayout(this);
TextView text = new TextView(this);
text.setText("Hello World");
text.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
layout.addView(text);
setContentView(layout);