【问题标题】:How can I define ImageView with height width and source defined on xml file?如何使用在 xml 文件中定义的高度宽度和源定义 ImageView?
【发布时间】:2020-11-13 02:06:33
【问题描述】:

片段上的膨胀视图导致删除属性,如何定义具有高度宽度和在 xml 文件中定义的源的 ImageView?

我正在使用下面的代码。对于 image_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.ImageFragment"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="test Image"
        tools:src="@drawable/cartoon" />
</LinearLayout>

对片段使用 kotlin 类

ImageFragment.kt

class ImageFragment : Fragment() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        val root = inflater.inflate(R.layout.image_fragment, container, false)


        return root
    }

}

它显示没什么。当我尝试调试工具时,我发现,imageview的高度和宽度没有定义,图像的资源也是如此。

只有当我使用

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        val root = inflater.inflate(R.layout.image_fragment, container, false)
        root.findViewById<ImageView>(R.id.imageView).setImageResource(R.drawable.cartoon)


        return root
    }

它是显示图像。但是属性仍然缺失。

那么在xml文件中定义属性和图片源应该怎么做呢?

【问题讨论】:

    标签: java android android-layout kotlin fragment


    【解决方案1】:

    您在xml 中使用tools,它只显示预览。

    你必须使用app:srcCompat:

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="test Image"
        app:srcCompat="@drawable/cartoon" />
    

    【讨论】:

      【解决方案2】:

      文件所说

      Android Studio 在工具中支持多种 XML 属性 启用设计时功能的命名空间(例如 显示在片段中)或编译时行为(例如收缩 模式应用到您的 XML 资源)。构建应用程序时, 构建工具删除这些属性,因此对您的 APK 没有影响 大小或运行时行为。

      所以tools:src="@drawable/cartoon" 仅在设计 UI 预览中显示,它将在 构建时删除
      使用app:srcCompat="@drawable/cartoon" 而不是tools:src="@drawable/cartoon"

      对于在您的 XML 文件中使用 app:srcCompat,请确保执行以下操作:
      设置你的 build.gradle 文件

      android {
        defaultConfig {
          vectorDrawables {
            useSupportLibrary = true
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        • 2021-09-11
        相关资源
        最近更新 更多