Wai*_*ein 7 android android-layout layout-inflater android-view android-viewgroup
我正在开发一款Android应用.在我的应用程序中,我需要动态地扩展视图列表.我加了他们并且正在工作.问题是设置布局的宽度和高度.现在我将通过一个简单的项目来演示我的问题.实际上,我的项目比这个简单的项目复杂得多.
我正在夸大这种布局的观点.
<LinearLayout
android:orientation="horizontal"
android:id="@+id/cm_photos_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
我循环遍历位图列表并动态添加视图,如下所示
for(Bitmap bmp : bitmaps)
{
View preview = layoutInflater.inflate(R.layout.item_cm_preview_image,null);
ImageView previewImageView = (ImageView)preview.findViewById(R.id.item_cm_preview_image);
previewImageView.setImageBitmap(bmp);
container.addView(preview);
}
Run Code Online (Sandbox Code Playgroud)
请注意,在上面的代码中,container是一个LinearLayout动态添加到上面的父XML中.
container = new LinearLayout(this);
container.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
container.setLayoutParams(params);
parentLinearLayout.addView(container);
Run Code Online (Sandbox Code Playgroud)
这是我的item_cm_preview_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_weight="1"
android:layout_height="400dp"
android:layout_width="0dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:scaleType="centerCrop"
android:id="@+id/item_cm_preview_image"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
如您所见,我在XML中将布局高度设置为400dp,宽度0和layout_weight为1.因此,由于layout_weight,所有图像高度必须相同且宽度必须相等.但结果并不像预期的那样.你可以在下面看到截图.
正如您在屏幕截图中看到的那样,layout_weight和height都不适用于所有膨胀的视图.但是,如果我动态添加额外的ViewGroup并将视图扩展到该布局,它就可以了.以下是我的代码
//This happening in for loop
LinearLayout wrapper = new LinearLayout(this);
wrapper.setLayoutParams(new LinearLayout.LayoutParams(0,500,1));
View preview = layoutInflater.inflate(R.layout.item_cm_preview_image,null);
ImageView previewImageView = (ImageView)preview.findViewById(R.id.item_cm_preview_image);
previewImageView.setImageBitmap(bmp);
wrapper.addView(preview);
container.addView(wrapper);
Run Code Online (Sandbox Code Playgroud)
这是结果:
当我使用额外的动态线性布局时,您可以看到layout_weight和height都工作.为什么在XML中设置布局权重和高度不起作用?为什么第二种方式有效?如何在XML布局文件中设置权重和高度?可能吗?
小智 21
如果使用方法扩充布局
View preview = layoutInflater.inflate(R.layout.item_cm_preview_image,null);
Run Code Online (Sandbox Code Playgroud)
它跳过它的宽度和高度参数......,但如果你将使用:
View preview = layoutInflater.inflate(R.layout.item_cm_preview_image,parent,false);
Run Code Online (Sandbox Code Playgroud)
它应该正常工作,例如,如果您将活动中的视图作为父级提供(ViewGroup)getView():
View preview = layoutInflater.inflate(R.layout.item_cm_preview_image,(ViewGroup) getView(), false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5375 次 |
| 最近记录: |