LayoutInflater,layoutinflater是什麼

來源:互聯網
上載者:User

LayoutInflater,layoutinflater是什麼
作用: 
1、對於一個沒有被載入或者想要動態載入的介面, 都需要使用inflate來載入. 

2、對於一個已經載入的Activity, 就可以使用實現了這個Activiyt的的findViewById方法來獲得其中的介面元素. 

方法: 
   Android裡面想要建立一個畫面的時候, 初學一般都是建立一個類, 繼承Activity基類, 然後在onCreate裡面使用setContentView方法來載入一個在xml裡定義好的介面. 

   其實在Activity裡面就使用了LayoutInflater來載入介面, 通過getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以獲得一個 LayoutInflater, 也可以通過LayoutInflater inflater = getLayoutInflater();來獲得.然後使用inflate方法來載入layout的xml, 
下面是一個簡單的例子:
首先我們要知道,什麼是已經被載入的layout,什麼是還沒有載入的.我們啟動一個應用,與入口Activity相關的layout{常見的是main.xml}就是被載入的,即在Oncreate()中的.而其他的layout是沒有被載入的.就要動態載入了或通過另一個activity.
在實際開發種LayoutInflater這個類還是非常有用的,它的作用類似於 findViewById(),不同點是LayoutInflater是用來找layout下xml布局檔案,並且執行個體化!而findViewById()是找具體xml下的具體 widget控制項.為了讓大家容易理解我[轉]做了一個簡單的Demo,主布局main.xml裡有一個TextView和一個Button,當點擊Button,出現 Dialog,而這個Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml檔案(裡面左右分布,左邊 ImageView,右邊TextView)。

代碼如下:package com.bivin;
import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button button;
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);button.setOnClickListener(this);}
@Overridepublic void onClick(View v) {
showCustomDialog();}
public void showCustomDialog() {AlertDialog.Builder builder;AlertDialog alertDialog;Context mContext = MainActivity.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.custom_dialog, null);TextView text = (TextView) layout.findViewById(R.id.text);text.setText("Hello, Welcome to Mr Wei's blog!");ImageView image = (ImageView) layout.findViewById(R.id.image);image.setImageResource(R.drawable.icon);builder = new AlertDialog.Builder(mContext);builder.setView(layout);alertDialog = builder.create();alertDialog.show();}}
android layoutinflater引入出來布局,怎顯示

setContentView(view);
 
android 怎初始化LayoutInflater的View裡面的文字框的值

settext(“xxx”);
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.