如何在Android中刷新自定义布局的视图?

时间:2015-10-02 05:40:19

标签: android android-layout

我正在创建一个自定义TitleBar,它是RelativeLayout的子类,并通过膨胀xml布局文件来创建其视图。其中有一个TextView来显示标题,TitleBar类有一个名为titleText的自定义属性。我在attrs.xml中对它进行了改进,并在onFinishInflate()中调用了mTitleText.setText(),它可以正常工作。

但后来我想以编程方式更改标题,因此我添加了一个公共方法setTitle(),其中修改了私有String变量mTitle并调用了invalidate()和requestLayout()。但是,它不起作用,我意识到onFinishInflate()只会被调用一次。那么如何更新TextView呢?我应该在哪里调用mTitleText.setText()?我应该覆盖onDraw()?

以下是我的一些代码:

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);
    }
}

2 个答案:

答案 0 :(得分:0)

public void updateTextView(String toThis) {
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(toThis);
}

答案 1 :(得分:0)

好吧,最后我通过阅读setTitle()的{​​{1}}方法找到了答案:

android.widget.Toolbar

事实证明,我只需要在public void setTitle(CharSequence title) { if (!TextUtils.isEmpty(title)) { if (mTitleTextView == null) { final Context context = getContext(); mTitleTextView = new TextView(context); mTitleTextView.setSingleLine(); mTitleTextView.setEllipsize(TextUtils.TruncateAt.END); if (mTitleTextAppearance != 0) { mTitleTextView.setTextAppearance(mTitleTextAppearance); } if (mTitleTextColor != 0) { mTitleTextView.setTextColor(mTitleTextColor); } } if (!isChildOrHidden(mTitleTextView)) { addSystemView(mTitleTextView, true); } } else if (mTitleTextView != null && isChildOrHidden(mTitleTextView)) { removeView(mTitleTextView); mHiddenViews.remove(mTitleTextView); } if (mTitleTextView != null) { mTitleTextView.setText(title); } mTitleText = title; } 中拨打mTitleText.setText()并同时更改TitleBar.setTitle()以便进一步使用。