【发布时间】:2019-05-28 13:46:45
【问题描述】:
我有一个自定义视图,可以在活动上膨胀:
class NeedMoreTimeScreen @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
fun inflate(context: Context) {
LayoutInflater
.from(context)
.inflate(R.layout.screen_more_time, this, true)
val inflatedView = LayoutInflater
.from(context)
.inflate(R.layout.screen_more_time, this, true)
inflatedView.visibility = View.VISIBLE
val countDownTextView = inflatedView.findViewById<TextView>(R.id.countDownText)
countDownTextView.text = "text I want to appear"
}
}
.xml 用于自定义视图:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/holder"
android:layout_width="768px"
android:layout_height="840px"
android:background="@color/main_background">
<TextView
android:text="10s"
android:textAppearance="@style/ScreenTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="160px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/countDownText"/>
</RelativeLayout>
</FrameLayout>
当我在它的 .xml 中给它文本时,文本出现在 TextView 中,但是以编程方式设置它似乎没有被执行。为什么?
【问题讨论】:
-
仔细查看重复通货膨胀,不要忘记调用
inflate()方法 -
设置文字后需要调用
invalidate()方法。 -
感谢您的回复。视图肯定在膨胀,文本只是没有出现。 invalidate() 听起来像我正在寻找的东西,但我应该什么时候调用它?在我尝试设置它们之前和之后在膨胀视图和文本视图上调用它似乎没有效果。
标签: android android-layout kotlin android-custom-view