0

使用 RelativeLayout 我正在尝试创建一个自定义 ViewGroup ,它将添加到 Activity 的 ScrollView 中。我创建了以下类来创建 ViewGroup。

public class MessageView extends RelativeLayout implements MessageType {

    View mView;
    public TextView messageText;

    public MessageView(Context context, int type) {
        super(context);

        MAX_LINE = getResources().getInteger(R.integer.MAX_LINE);
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (type == MESSAGEFROM) {
            inflater.inflate(R.layout.message_layout_from, this, true);
        } else {
            inflater.inflate(R.layout.message_layout_to, this, true);
        }
    }

    @Override
    public void onFinishInflate() {
        Log.d("MessageView", "Finished Inflation");
        super.onFinishInflate();
        addView(mView, 0);
        messageText = (TextView) findViewById(R.id.messageText);
    }

    public void setText(String s) {
        this.messageText.setText(s);
    }

在主要活动中,我正在创建新的 MessageView,如下所示,

MessageView a = new MessageView(getApplicationContext(), MESSAGEFROM);
a.setText(message);
chatRoom.addView(a);

但是onFinishInflate()方法从未调用过,我nullPointerExceptiona.setText(message). 如果在构造函数中使用以下行,我会遇到同样的错误MessageView()

messageText = (TextView) findViewById(R.id.messageText);
4

1 回答 1

0

我认为问题在于RelativeLayout 不知道如何找到textview。我假设您的文本视图来自膨胀的 xml 文件。所以我说使用存储对膨胀视图的引用,然后使用 findViewById

在代码中,

View inflated = inflater.inflate(R.layout.message_layout_from, this, true);
messageText = (TextView) inflated.findViewById(R.id.messageText);

该 id 通常在布局 XML 文件中分配,但您采用了不同的方法(扩展 RelativeLayout)

于 2014-12-21T06:40:55.897 回答