LayoutInflater作用及使用
生活随笔
收集整理的這篇文章主要介紹了
LayoutInflater作用及使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
作用:?
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,?
代碼如下: 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 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(); } }
轉(zhuǎn)載于:https://www.cnblogs.com/raffeale/p/4564415.html
總結(jié)
以上是生活随笔為你收集整理的LayoutInflater作用及使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (王道408考研操作系统)第四章文件管理
- 下一篇: SQL注入:3、无权读取informat