0

ScrollView我試圖創建一個自定義的ViewGroup,它將被添加到活動中的ScrollView中。我創建了以下類來創建ViewGroup。使用RelativeLayout自定義子項RelativeLayout添加到活動

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 a = new MessageView(getApplicationContext(), MESSAGEFROM); 
a.setText(message); 
chatRoom.addView(a); 

onFinishInflate()方法從來沒有所謂的,我在a.setText(message)越來越nullPointerException錯誤。如果在構造函數MessageView()中使用以下行,我會得到同樣的錯誤。

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

回答

0

我認爲問題在於RelativeLayout不知道如何找到文本視圖。我假設你的文本視圖來自膨脹的XML文件。所以我說用店裏充氣視圖的引用,然後使用findViewById

在代碼中,

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

該ID是佈局XML文件中通常被分配但你用不同的方法去(擴展的RelativeLayout)

+0

謝謝你的工作。 – saikat

+0

你能標記爲已接受的答案嗎? – committedandroider