1、对于一个没有被载入或者想要动态载入的界面, 都需要使用inflate来载入.
2、对于一个已经载入的Activity,就可以使用实现了这个Activiyt的的findViewById方法来获得其中的界面元素.
方法:
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();
}
}
从LayoutInflater的API的介绍中可以知道,该类是主要用于对XML文件的转化成一个响应的视图对象的类。应用该功能之前还需声明一个LayoutInflater工厂对象。有三种方法可以使用:
1、LayoutInflater factory = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2、LayoutInflater factory = (LayoutInflater)LayoutInflater.from(context);
3、LayoutInflater factory = (LayoutInflater)context.getLayoutInflater();
其中:context是对应的Activity类名。
方法2中调用了方法1。
方法3中不太清楚实现细节。知道的可以赐教。
接下来可以使用LayoutInflater对象的inflater的各种不同的方法来生产XML相应的对象。
在下面就是把该XML对象加入到响应的容器当中。可以是AlterDialog.Builder当中。调用该容器的setView方法即可。
另外getSystemService()是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。
传入的Name | 返回的对象 | 说明 |
WINDOW_SERVICE | WindowManager | 管理打开的窗口程序 |
LAYOUT_INFLATER_SERVICE | LayoutInflater | 取得xml里定义的view |
ACTIVITY_SERVICE | ActivityManager | 管理应用程序的系统状态 |
POWER_SERVICE | PowerManger | 电源的服务 |
ALARM_SERVICE | AlarmManager | 闹钟的服务 |
NOTIFICATION_SERVICE | NotificationManager | 状态栏的服务 |
KEYGUARD_SERVICE | KeyguardManager | 键盘锁的服务 |
LOCATION_SERVICE | LocationManager | 位置的服务,如GPS |
SEARCH_SERVICE | SearchManager | 搜索的服务 |
VEBRATOR_SERVICE | Vebrator | 手机震动的服务 |
CONNECTIVITY_SERVICE | Connectivity | 网络连接的服务 |
WIFI_SERVICE | WifiManager | Wi-Fi服务 |
TELEPHONY_SERVICE | TeleponyManager | 电话服务 |