我想编写自己的自定义视图(View),但是在LayoutParams方面遇到了问题。
我的想法是扩展ViewGroup(LinearLayout)。
问题在于:项目根元素的属性被忽略了。
我的想法是扩展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);
}
}
}
正如你所看到的,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>
主屏幕布局
<?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>
活动代码
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();
}
}
这是我得到的截图。
![enter image description here](https://istack.dev59.com/EG5Of.webp)
android:layout_width="match_parent"
android:layout_height="match_parent"
但是我希望得到类似于这样的结果(当使用这行代码代替addView(view);
时,我得到了这个结果)
addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F));
如何在不使用硬编码的LayoutParams的情况下实现此结果呢?感谢任何帮助!
更新
我还查看了调试模式下的view
变量字段-mLayoutParams
为null
,当我使用addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F))
将充气的view
添加到父级时,它变成了非空。
但是刚加载的视图的子元素的mLayoutParams
不为空。
为什么在视图充气时只忽略xml布局中根元素的LayoutParams?
ll
,我将给定的 XML 填充并放入ll
中。 - Max Komarychevnew LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F)
并将其传递给addView
方法时,与v
一起使用时,它能正常工作!(在这种情况下,边距被忽略) - Max Komarychev