Android 如何在Kotlin中设置文本内容自定义文本视图
我只是在Kotlin中创建了名为MyTextView的自定义TextView和XML布局Android 如何在Kotlin中设置文本内容自定义文本视图,android,kotlin,textview,Android,Kotlin,Textview,我只是在Kotlin中创建了名为MyTextView的自定义TextView和XML布局 class MyTextView : TextView { constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } construct
class MyTextView : TextView
{
constructor(context: Context) : super(context)
{
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
{
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
{
init()
}
private fun init()
{
this.paintFlags = this.paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
}
上面写着,未解决的引用。怎么办
它适用于普通文本视图。请先导入布局文件
import kotlinx.android.synthetic.main.layout_name.mytextview
将文本设置为textview需要可编辑实例
请给科特林试试这个
mytextview.text = Editable.Factory.getInstance().newEditable("hi")
很可能您没有在布局中引用自定义TextView的包名称,而activity inflater不知道在哪里可以找到该视图(自定义TextView)。确保在布局中引用了包名称,如下所示:
<your.package.name.MyCustomTextView />
试试这个代码
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
试试看:
var mytextview = findViewById(R.id.mytextview) as TextView
之后,您可以像java一样尝试:
Toast.makeText(this, mytextview.getText(), Toast.LENGTH_SHORT).show()
我希望它能帮助你 想到一个定制的文本视图真是太奇怪了。。。您是否可以在布局中创建一个TextView,然后通过findViewById为该TextView创建一个引用,然后尝试通过setText更改文本?customTextView的id是什么?是不是
mytextview
?请发布您的xml布局。是的。。。id是mytextview,我正在使用extensions@sanoJI粘贴我的xml布局代码,不需要这样做。文本字符串应该从box@MikeM. 哈哈哈,刚刚发现了…拼写检查和自动更正尝试修复我的拼写错误,一切都完成了。但不起作用。请看上面,我已经添加了代码,我正在使用androidextensions@Emilyjohn同样的概念仍然适用。您将在自定义textview代码文件的顶部找到程序包名称。。
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
var mytextview = findViewById(R.id.mytextview) as TextView
Toast.makeText(this, mytextview.getText(), Toast.LENGTH_SHORT).show()