赞
踩
有两种方式
1.
LayoutInflater layoutInflater= LayoutInflater.from(MainActivity.this);
LayoutInflater layoutInflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:text="Button"
android:layout_width="300dp"
android:layout_height="wrap_content">
</Button>
package yuexia.com.customview; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { private RelativeLayout rl_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rl_content = (RelativeLayout) this.findViewById(R.id.rl_content); LayoutInflater inflater = LayoutInflater.from(MainActivity.this); LayoutInflater layoutInflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); /* * 子元素属性的实现的两种方式 * 1.root添加父元素 * 2.给子元素添加布局 * */ View view=layoutInflater.inflate(R.layout.button,rl_content,true); // rl_content.addView(view); /* * 关于inflate的使用 * 1.inflate的方法中root和attachToRoot分别不为空和true的时候就会添加view不需要再addView() * 2.添加merge时root和attachToRoot分别必须不为空和必须为true,所以也就用不到addView() * */ } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。