Search code examples
androidandroid-layoutandroid-scrollviewandroid-viewgroup

Custom child RelativeLayout to add into ScrollView in Activity


Using RelativeLayout I am trying to create a custom ViewGroup which will be added inside the ScrollView in the Activity. I have created following class to create 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);
    }

In the main activity, I am creating new MessageView as follow,

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

But onFinishInflate() method never called and I am getting nullPointerException error at a.setText(message). The same error I am getting, if following line is used in the constructor MessageView().

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

Solution

  • I think the issue is that RelativeLayout doesn't know how to find the textview. I am assuming that your text view comes from the inflated xml file. So I say use store a reference to the inflated view and then use findViewById

    In code,

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

    That id is usually assigned in the layout XML file but you went with a different approach(extending RelativeLayout)