日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LayoutInflater作用及使用

發布時間:2025/3/15 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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); } @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(); } }

轉載于:https://www.cnblogs.com/raffeale/p/4564415.html

總結

以上是生活随笔為你收集整理的LayoutInflater作用及使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。