android LayoutInflater 使用樣本《轉載》

來源:互聯網
上載者:User
android LayoutInflater 使用樣本《轉載》
大家好我們這一節講的是LayoutInflater的使用,在實際開發種LayoutInflater這個類還是非常有用的,它的作用類似於 findViewById(),

不同點是LayoutInflater是用來找layout下xml布局檔案,並且執行個體化!而findViewById()是找具體xml下的具體 widget控制項(如:Button,TextView等)。

為了讓大家容易理解我做了一個簡單的Demo,主布局main.xml裡有一個TextView和一個Button,當點擊Button,出現 Dialog,而這個Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml檔案(裡面左右分布,左邊 ImageView,右邊TextView)。下面我們看一下運行效果吧。

布局檔案
main.xml

custom_dialog.xml

Activity01 類
Java代碼

* package xiaohang.zhimeng;
*

*

* 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 Activity01 extends Activity implements OnClickListener{
*

* private Button button;
*

* @Override
* public
void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* setContentView(R.layout.main);
* button = (Button)findViewById(R.id.myButton);
* button.setOnClickListener(this);
* }
*

* @Override
* public
void onClick(View v) {
* showCustomDialog();
* }
*

* public
void showCustomDialog(){
* AlertDialog.Builder builder;
* AlertDialog alertDialog;
* Context mContext = Activity01.this;
*

* //下面3種方法都可以
* //LayoutInflater inflater = getLayoutInflater();
* // mInflater = LayoutInflater.from(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 xh blog");
* ImageView image = (ImageView)layout.findViewById(R.id.image);
* //給ImageView 設定表徵圖
* image.setImageResource(R.drawable.icon);
* builder = new AlertDialog.Builder(mContext);
* builder.setView(layout);
* alertDialog = builder.create();
* alertDialog.show();
* }
* }

聯繫我們

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