[英]Text not being set in inflated view's TextView
我有一個自定義視圖,通過一個活動膨脹:
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中,但是以編程方式設置它似乎不會被執行。 為什么?
試試下面的代碼,
public class NeedMoreTimeScreen : RelativeLayout
{
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()
{
// apply your inflation code here
val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
layoutInflater.inflate(R.layout.screen_more_time, this, true)
countDownTextView.text = "text I want to appear"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.