溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

LayoutInflater類

發(fā)布時(shí)間:2020-06-15 05:25:54 來源:網(wǎng)絡(luò) 閱讀:194 作者:JustMetU 欄目:移動(dòng)開發(fā)

作用: 
1、對(duì)于一個(gè)沒有被載入或者想要?jiǎng)討B(tài)載入的界面, 都需要使用inflate來載入. 

2、對(duì)于一個(gè)已經(jīng)載入的Activity, 就可以使用實(shí)現(xiàn)了這個(gè)Activiyt的的findViewById方法來獲得其中的界面元素. 

方法: 
  Android里面想要?jiǎng)?chuàng)建一個(gè)畫面的時(shí)候, 初學(xué)一般都是新建一個(gè)類, 繼承Activity基類, 然后在onCreate里面使用setContentView方法來載入一個(gè)在xml里定義好的界面. 

  其實(shí)在Activity里面就使用了LayoutInflater來載入界面, 通過getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以獲得一個(gè) LayoutInflater, 也可以通過LayoutInflater inflater = getLayoutInflater();來獲得.然后使用inflate方法來載入layout的xml, 


下面是一個(gè)簡單的例子:


首先 我們要知道,什么是已經(jīng)被載入的layout,什么是還沒有載入的.我們啟動(dòng)一個(gè)應(yīng)用,與入口Activity相關(guān)的layout{常見的是 main.xml}就是被載入的,即在Oncreate()中的.而其他的layout是沒有被載入的.就要?jiǎng)討B(tài)載入了或通過另一個(gè)activity.


在實(shí)際開發(fā)種LayoutInflater這個(gè)類還是非常有用的,它的作用類似于 findViewById(),

不同點(diǎn)是LayoutInflater是用來找layout下xml布局文件,并且實(shí)例化!而findViewById()是找具體xml下的具體 widget控件.

為了讓大家容易理解我[轉(zhuǎn)]做了一個(gè)簡單的Demo,主布局main.xml里有一個(gè)TextView和一個(gè)Button,當(dāng)點(diǎn)擊Button,出現(xiàn) Dialog,而這個(gè)Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml文件(里面左右分布,左邊 ImageView,右邊TextView)。

LayoutInflater類

代碼如下:

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);

}


@Override

public 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 p_w_picpath = (ImageView) layout.findViewById(R.id.p_w_picpath);

p_w_picpath.setImageResource(R.drawable.icon);

builder = new AlertDialog.Builder(mContext);

builder.setView(layout);

alertDialog = builder.create();

alertDialog.show();

}

}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI