我有一个自定义视图,它会在活动上膨胀:
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文本提供文本时,文本将显示在文本视图中,但以编程方式设置它似乎没有执行。为什么?
尝试下面的代码,
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"
}
}