mytext.xml
<TextView xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”wrap_content”
android:layout_height=”fill_parent”
android:gravity=”center”
android:textColor=”#ff0000″
android:textSize=”20px”
android:background=”#000000″
android:text=”TextView”
/>
Inflation.java
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import android.view.ViewGroup.*;
import android.widget.*;
public class Inflation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linear = new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
linear.setBackgroundColor(Color.YELLOW);
TextView text = (TextView)View.inflate(this, R.layout.mytext, null);
linear.addView(text);
setContentView(linear);
}
}
위와 같은 형태로 mytext 뷰를 inflate() 함수를 통해 전개할 때 mytext 뷰에서 정의된 layout_width, layout_height 속성은 적용되지 않는다. 이것은 inflate()를 사용하는 특성 때문인 것 같다. inflate() 함수를 쓴다는 얘긴 동적으로 뷰를 집어넣는 다는 것인다. ViewGroup이 어떤 것인지 알려지지 않은 상태에서는 layout_width, layout_height 을 지정할 수 없는 것 같다.
이러한, 경우 addView()함수를 통해 부모와의 관계를 정의할 때 레이아웃 파라미터를 설정함으로써 변경이 가능하다.
Inflation2.java
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import android.view.ViewGroup.*;
import android.widget.*;
public class Inflation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linear = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT);
linear.setOrientation(LinearLayout.VERTICAL);
linear.setBackgroundColor(Color.YELLOW);
TextView text = (TextView)View.inflate(this, R.layout.mytext, null);
linear.addView(text, params);
setContentView(linear);
}
}