Android自訂View的學習(一)

來源:互聯網
上載者:User

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如下:

        




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.