如何从自定义xml文件访问textview?

时间:2019-10-16 06:42:42

标签: java android

我想访问一个名为user_status的文本视图,该视图位于自定义xml布局文件中,以便用一些数据填充它。我想从我的主要活动java类访问它。我该怎么做呢?我已经在堆栈溢出中尝试了一些答案,但它要么无法正常工作,要么已过时。

LayoutInflater inflater = MessageActivity.this.getLayoutInflater();
                    View inflatedView = inflater.inflate(R.layout.message_row, null);
                    TextView userMessage= (TextView) inflatedView.findViewById(R.id.user_status);
                    userMessage.setText("NEW MESSAGE DUMMMY!");

2 个答案:

答案 0 :(得分:1)

使用

TextView userMessage = inflatedView.findViewById(R.id.user_status);
userMessage.setText("NEW MESSAGE DUMMMY!");

答案 1 :(得分:0)

要在MainActivity中实现此目的,您应该先添加视图,然后找到TextView,或者可以将自定义布局文件包含在MainActivity的xml布局中。

“添加视图”可以找到here

包含布局可以找到here