【发布时间】: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