歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:LayoutInflater的應用

Android開發教程:LayoutInflater的應用

日期:2017/3/1 10:36:24   编辑:Linux編程

LayoutInflater在Android中是“擴展”的意思,作用類似findViewById( ),它在Android開發中的作用是很大的。LayoutInflater經常在BaseAdapter的getView方法中用到,用來獲取整個View並返回。

LayoutInflater與findViewById( )的不同點:

  • LayoutInflater是將XML中的Layout轉換為View放入.java代碼中
  • findViewById()是找具體xml下的具體組件(如:Button,TextView,ImageView等)。

獲得LayoutInflater的三種方法:

第一種:

  1. LayoutInflater inflater = LayoutInflater.from(this);
  2. View layout = inflater.inflate(R.layout.main, null);

第二種:

  1. LayoutInflater inflater = getLayoutInflater();
  2. View layout = inflater.inflate(R.layout.main, null);

第三種:

  1. LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
  2. View layout = inflater.inflate(R.layout.main, null);

getSystemService()是Android很重要的一個API,它是Activity的一個方法,根據傳入 的NAME來取得對應的Object,然後轉換成相應的服務對象。以下介紹系統相應的服務。其中LAYOUT_INFLATER_SERVICE返回的對象是 LayoutInflater,作用是取得XML定義的View。

第一個實例:

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <EditText
  8. android:id="@+id/text"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. />
  12. <Button
  13. android:id="@+id/btn1"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content"
  16. />
  17. <Button
  18. android:id="@+id/btn2"
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content"
  21. />
  22. </LinearLayout>

MainActivity.java

  1. package com.lingdududu.test;
  2. import android.app.Activity;
  3. import android.graphics.Color;
  4. import android.os.Bundle;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. public class MainActivity extends Activity {
  10. private EditText etx;
  11. private Button confirmBtn;
  12. private Button cancleBtn;
  13. /** Called when the activity is first created. */
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. LayoutInflater inflater = getLayoutInflater();
  18. View layout = inflater.inflate(R.layout.main, null);
  19. etx = (EditText)layout.findViewById(R.id.text);
  20. etx.setBackgroundColor(Color.WHITE);
  21. etx.setHint("請輸入你的學號");
  22. confirmBtn = (Button)layout.findViewById(R.id.btn1);
  23. confirmBtn.setText("確定");
  24. cancleBtn = (Button)layout.findViewById(R.id.btn2);
  25. cancleBtn.setText("取消");
  26. setContentView(layout);
  27. }
  28. }

效果圖:

650) this.width=650;">

Copyright © Linux教程網 All Rights Reserved