title: How to refresh the view of a custom layout in Android?
body: <p>I am creating a custom TitleBar which subclasses RelativeLayout and creates its view by inflating an xml layout file. There's a TextView in it to display title, and the TitleBar class has a custom attribute called titleText. I have difined it in attrs.xml and called mTitleText.setText() in onFinishInflate(), and it works properly.</p>
  
  <p>But then I want to change the title programmatically, so I add a public method setTitle(), in which the private String variable mTitle is modified and invalidate() and requestLayout() are called. However, it doesn't work and I realize that onFinishInflate() will be called only once. So how to update the TextView? Where should I call mTitleText.setText()? Should I override onDraw()?</p>
  
  <p>Here is some of my code:</p>
  
  <pre><code>public class TitleBar extends RelativeLayout {
      private String mTitle;
      private TextView mTitleText;
  
      public TitleBar(Context context, AttributeSet attrs) {
          super(context, attrs);
          retrieveProperties(context, attrs);
          initializeView(context);
      }
  
      public String getTitle() {
          return mTitle;
      }
  
      public void setTitle(String title) {
          mTitle = title;
          invalidate();
          requestLayout();
      }
  
      private void retrieveProperties(Context context, AttributeSet attrs) {
          TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TitleBar, 0, 0);
          try {
              mTitle = a.getString(R.styleable.TitleBar_titleText);
          } finally {
              a.recycle();
          }
      }
  
      private void initializeView(Context context) {
          setWillNotDraw(false);
          ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.title_bar, this);
      }
  
      @Override
      protected void onFinishInflate() {
          super.onFinishInflate();
          mTitleText = (TextView)findViewById(R.id.title_text);
          mTitleText.setText(mTitle);
      }
  }
  </code></pre>