【问题标题】:Text not being set in inflated view's TextView未在膨胀视图的 TextView 中设置文本
【发布时间】: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


【解决方案1】:

试试下面的代码,

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"
    }
}

【讨论】:

  • 不幸的是,这没有效果。
  • 只有上面的代码。我只是把它叫做 inflate() 而不是 init()
  • 对不起,没有变化:/
  • 现在不可能,我认为你在某个地方犯了错误,我正在使用相同的代码进行自定义视图
猜你喜欢
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多