Max*_*hev 38 layout android layoutparams
我正在尝试编写自己的习惯View,但我遇到了问题LayoutParams.
想法是扩展ViewGroup(LinearLayout)
public class MyView extends LinearLayout{
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
}
public void putContent(){
setOrientation(HORIZONTAL);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 5; i++){
View view = inflater.inflate(R.layout.item, null);
TextView tv = (TextView)view.findViewById(R.id.item_text);
tv.setText("Item " + i);
addView(view);
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,putContent方法会使项目膨胀并添加到我的视图中.这是一个项目布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<TextView android:text="TextView"
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
和主屏幕布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android_layout_weight="1"
android:text="@string/hello"
/>
<my.test.MyView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android_layout_weight="1"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
和活动代码
public class Start extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyView myView = (MyView)findViewById(R.id.my_view);
myView.putContent();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的截图

所以问题是:项的根元素的属性被忽略
android:layout_width="match_parent"
android:layout_height="match_parent"
Run Code Online (Sandbox Code Playgroud)
但结果我想得到这样的东西(当addView(view);用这条线替换时我得到这个结果)
addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F));
Run Code Online (Sandbox Code Playgroud)

所以问题是:如果没有硬编码的LayoutParams,我怎么能实现这个结果?谢谢你的帮助!
更新
我也看view变量域在调试模式- mLayoutParamsIS null,并成为当我添加充气NOT NULL view为母公司同addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F));.
但mLayoutParams刚刚加载的视图的子项不为null.为什么在视图膨胀时忽略xml布局中只有根元素的LayoutParams?
Kar*_*ran 122
使用以下语句来膨胀:
View view = inflater.inflate( R.layout.item /* resource id */,
MyView.this /* parent */,
false /*attachToRoot*/);
Run Code Online (Sandbox Code Playgroud)