Android Layout 中XML 加载模块的方式总结

在Android开发中,对于在Xml文件中布局块的加载常见的就是include的静态加载ViewStub的动态加载

(1)静态加载



是在布局加载的过程中,同时加载,被加载的模块和其他模块加载的时间一样。

静态加载的基本使用

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   

            android:id="@+id/showBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button1" />

(2)动态加载

需要被加载的模块初始时没有被加载进内存,当需要使用的时候才会被动态加载进内存。ViewStub 本质上也是一个View  他的继承关系 Object<- View<-ViewStub  ,在性能优化方面是常见的,因为只要不需要就不用加载他,因为像其他布局只要存在,初始化就会加载,虽然设置了Gone 但是他们依然占据着内存。ViewStub加载完以后就会自我移除,ViewStub的子控件会交给父布局来处理,ViewStub只能被加载一次。想要布局加载两次就得需要应用重启。ViewStub不能加载具体的View,需要加载具体的布局文件。

ViewStub的属性和方法

Android Layout 中XML 加载模块的方式总结_第1张图片

布局文件

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

            android:id="@+id/showBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button1" />
          android:id="@+id/vs"
        android:layout="@layout/viewstub"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

java文件
public class MainActivity extends AppCompatActivity {
    private ViewStub viewStub;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewStub = (ViewStub) findViewById(R.id.vs);
        //textView  = (TextView) findViewById(R.id.hello_tv);// 空指针   ViewStub加载的布局中的控件,因为此时ViewStub还未初始化,所以子控件还是找不到的。
    }
    public  void inflate(View view){
        viewStub.inflate();
        //textView  = (TextView) viewStub.findViewById(R.id.hello_tv);空指针  viewStub已经被移除了
        textView  = (TextView) findViewById(R.id.hello_tv);
    }
    public void setData(View view){
        textView.setText("Hello ");

    }
}

你可能感兴趣的:(Android学习总结)