MainActivity如下:
package cc.testviewstudy1;import android.os.Bundle;import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewParent;import android.widget.RelativeLayout;/** * Demo描述: * 關於自訂View的學習(一) * * 學習資料: * http://blog.csdn.net/guolin_blog/article/details/12921889 * Thank you very much * */public class MainActivity extends Activity { private RelativeLayout mRelativeLayout; private LayoutInflater mLayoutInflater;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);init();//test1();test2();test3();}//每個Activity由兩部分組成.//1 title//2 contentView//我們可以分別設定它們private void init(){setTitle("This is title");setContentView(R.layout.main);}//用button_layout_wrong布局的方式來在View中新加一個Button//是不夠準確的.因為此時我們是無法通過 android:layout_width和 android:layout_height//指定Button的寬和高,最終Button顯示的只有wrap_content的大小.private void test1(){mRelativeLayout=(RelativeLayout) findViewById(R.id.relativeLayout);mLayoutInflater=LayoutInflater.from(MainActivity.this);View buttonView=mLayoutInflater.inflate(R.layout.button_layout_wrong, null);mRelativeLayout.addView(buttonView);}//怎麼解決test1中的問題呢?//關鍵在於android:layout_width和 android:layout_height的理解//它指的是的控制項在布局中的寬和高所以叫android:layout_width和 android:layout_height//而不是叫android:width和 android:height.//所以,我們要先把控制項放在一個布局裡面,然後再給該控制項指定寬和高.這樣才有效果.//如:button_layout_right所示private void test2(){mRelativeLayout=(RelativeLayout) findViewById(R.id.relativeLayout);mLayoutInflater=LayoutInflater.from(MainActivity.this);View buttonView=mLayoutInflater.inflate(R.layout.button_layout_right, null);mRelativeLayout.addView(buttonView);}//繼續上面的例子://我們在每次布局的時候不是可以在最外層的布局通過android:layout_width和 android:layout_height//來指定該布局的寬和高麼然後setContentView()將其顯示在螢幕上的嗎?//這個最大的View沒有再嵌套一層布局為什麼可以指定寬和高呢?//這不是和上面的例子衝突了嗎?//其實,不是的.//因為在載入每個布局檔案xml的時候.不論其根布局是什麼,都會將該布局//外面嵌套一層FrameLayout.//這樣就和上面的例子統一了.private void test3(){mRelativeLayout=(RelativeLayout) findViewById(R.id.relativeLayout);ViewParent viewParent=mRelativeLayout.getParent();System.out.println("每個布局檔案的最外層的實質是:"+viewParent);}}
main.xml如下:
button_layout_wrong.xml如下:
button_layout_right.xml如下: