如何在Kotlin中创建View类对象?什么是AttributeSet?如何为视图创建它? [英] How to create View class object in Kotlin? What is AttributeSet? How to create it for a view?

查看:185
本文介绍了如何在Kotlin中创建View类对象?什么是AttributeSet?如何为视图创建它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,我有两个类文件MainActivity和CanV.

In Android, I have two class files, MainActivity and CanV.

MainActivity.kt

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

CanV.​​kt,这是一个View类.

CanV.kt, This is a View class.

class CanV(context: Context, attributeSet: AttributeSet): View(context){ ... }

activity_main.xml中的CanV视图

CanV view in activity_main.xml

<com.app.app_name.CanV
            android:id="@+id/cans"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="60dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0">
</com.app.app_name.CanV>

现在,我想在MainActivity中创建CanV类对象. 我来尝试: val c: CanV = CanV(this, ?)

Now I want to create CanV class object in MainActivity. I came to try: val c: CanV = CanV(this, ?)

但是,我不知道AttributeSet参数值.如何创建和传递CanV视图的AttributeSet?

But, I don't know the AttributeSet parameter value. How do I create and pass the AttributeSet of CanV view?

推荐答案

如果您希望能够同时从XML和Java/Kotlin创建CanV的实例,则应提供两个构造函数:

If you want to be able to create instances of CanV from both XML and Java/Kotlin, you should provide two constructors:

class CanV : View {

   constructor(context: Context) : super(context)
   constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

   ...
}

第一个可以在Kotlin(val v: CanV = CanV(this))中使用,第二个可以在从XML扩展时自动使用.

The first can be used from Kotlin (val v: CanV = CanV(this)), and the second is used automatically when inflating from XML.

这篇关于如何在Kotlin中创建View类对象?什么是AttributeSet?如何为视图创建它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆