• 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控件.

    为了让大家easy理解我[转]做了一个简单的Demo,主布局main.xml里有一个TextView和一个Button,当点击Button,出现 Dialog,而这个Dialog的布局方式是我们在layout文件夹下定义的custom_dialog.xml文件(里面左右分布,左边 ImageView,右边TextView)。
    LayoutInflater作用及使用

    代码例如以下:
    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();
    }
    }
  • 相关阅读:
    idea 红线 并提示idea cant resolve symbol
    shell 脚本不能执行多条?何解
    怎么在linux下创建一个可运行脚本?
    java linux sdk1.8
    Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:co
    什么是结构化数据和非结构化数据?什么是数据清洗?
    Installation failed with message Failed to finalize session: INSTALL_FAILED_TEST_ONLY:installPackageLI.
    Tensorflow-目标检测之yolov3训练自己的模型
    Tensorflow-目标检测之yolov3训练自己的模型
    《C#高效编程》读书笔记11-理解短小方法的优势
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7086606.html
Copyright © 2020-2023  润新知