Android之LayoutInflater

(一)LayoutInflater簡介

   LayoutInflater最重要的功能就是將XML文件實例化爲View對象,可以通過getSystemService(Context.LAYOUT_INFLATER_SERVICE)或getLayoutInflater()或的LayoutInflater對象,通過inflate方法來載入layout的xml。

(二)代碼實現

MainActivity代碼

package com.example.mydialog;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ArrayList<HashMap<String, Object>> listItem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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.mydialog, null);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("LayoutInflater妙用");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.albums);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
mydialog.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    
    >
    <ImageView android:id="@+id/image"
        android:layout_width="38dp"
        android:layout_height="38dp"
        />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        android:layout_centerVertical ="true"
        android:textColor="#000000" />

</RelativeLayout>

效果圖

wKiom1OMZjqCJOs2AABMR9D_6mg025.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章