我已经看了很多关于什么是 android 的通货膨胀的帖子,但我仍然不明白。有人可以详细描述它是什么以及我为什么需要它吗?他们说它用 XML 代码创建了一个对象,并且可以使用什么的。我几乎了解其他所有内容,但这对我来说没有意义。
3 回答
基本上是为了使您的逻辑部分与您的 UI 部分不同,XML 的概念出现了。
1- 在 XML 中创建 UI 非常简单且非常清晰。
2-通过这种隔离,我们可以选择为陆地/肖像/小/正常/较大模式创建不同的用户界面......
在运行时,XML 只是被解析并从中创建对象。
在使用 MVP 的 Android 程序结构中,即视图处理演示者和设计,即布局 xml。所以我们需要通过定义其他布局来定义xml的逻辑,并且经常用于维护UI操作,即改变UI行为。因此,它使我们通过膨胀将布局 xml 加载到其相应的视图对象中进行操作变得容易。
通过膨胀它我们可以访问相应的 UI 到视图对象。这个大家都知道。考虑活动课中的场景
class Activity1 extends Activity{
setContentView(R.layout.Mainlayout);
//here we are inflating the
//view into objects actually
//its is defined in earlier version as
//setContentView(getInflater().inflater(R.layout.MainLayout)
Button b=(Button)findViewById(R.id.button1);
}
但是如果你写
class Activity1 extends Activity{
Button b=(Button)findViewById(R.id.button1);//if called then there will be no errror but form runtimeexception Because of absence of setContext()
}
因此,为了派生类中的每个ui,我们需要通货膨胀但事实是android制造商已经在setContentView(),addview等中加入了通货膨胀,因此初学者无法理解通货膨胀这很简单但需要理解我们可以简单地编写if按钮。 xml 只有按钮
Button b=(Button)getInflater().inflate(R.layout.button);
在 Android 中,LayoutInflator负责解释这样的 xml 布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/ticketWeb"
/>
</RelativeLayout>
并且根据 xml 中的属性,它将“膨胀”或实例化 xml 布局中每个项目的 java 对象表示。因此,如果您有一个包含此 xml 文件的项目,inflator 将创建您可以使用 findViewById() 检索的 java 对象。一旦您检索到对这些对象的引用,您就可以调用它们的各种方法来影响关于它们的不同事物。