未在展开视图的TextView中设置文本

时间:2019-05-28 13:46:45

标签: android android-layout kotlin android-custom-view

我有一个自定义视图,可以放大活动:


export function myAction(componentClb: () => void): any {
  return (dispatch: Dispatch<AppStore>): void => {
    someRESTAPIcall()
      .then((condition) => {
        condition
          ? dispatch(anotherActionThatTakesCallbackAsArgument(componentClb))
          : componentClb();
      })
      .catch((error: Error) => {
        dispatch(myErrorAction());
      });
  };
}

.xml用于自定义视图:

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格式输入文本时,该文本会出现在TextView中,但是以编程方式设置它似乎并没有执行。为什么?

1 个答案:

答案 0 :(得分:0)

尝试以下代码,

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