[英]custom android view does not update when `invalidate` is called
我正在尝试创建用于分页的自定义视图。
这是代码:
public class PagerView extends LinearLayout {
private Button mPrevButton;
private Button mNextButton;
private TextView mInformationTextView;
public PagerView(Context context) {
this(context, null);
}
public PagerView(Context context, AttributeSet attrs) {
super(context, attrs);
this.initChild(context, attrs);
}
private void initChild(Context context, AttributeSet attrs) {
this.setOrientation(LinearLayout.HORIZONTAL);
this.setVisibility(GONE);
mPrevButton = new Button(context);
mPrevButton.setText("Prev");
mNextButton = new Button(context);
mNextButton.setText("Next");
mInformationTextView = new TextView(context);
mInformationTextView.setText("");
addView(mPrevButton);
addView(mInformationTextView);
addView(mNextButton);
}
public void setPageInformation(int page, int totalPage) {
if (page >= 1 && totalPage >= 1) {
this.setVisibility(VISIBLE);
if (totalPage > 1) {
mInformationTextView.setText(page + "/" + totalPage);
mPrevButton.setEnabled(page != 1);
mNextButton.setEnabled(page != totalPage);
}
} else
this.setVisibility(GONE);
postInvalidate();
}
}
和呼叫者:
public class PoiListActivity extends ActionBarActivity {
private ListView mListView;
private PagerView mPageBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poi_result_layout);
setupListView();
PoiResult poiResult = (PoiResult) GlobalState.getInstance().get(IConstant.Search_Result);
if (poiResult != null) {
refreshListView(poiResult);
}
}
private void refreshListView(PoiResult poiResult) {
mPageBar.setPageInformation(1, 3);
mAdapterItems.clear();
mAdapterItems.addAll(poiResult.poiList);
mAdapter.notifyDataSetChanged();
}
private void setupListView() {
mPageBar = new PagerView(this, this);
mListView = (ListView) findViewById(R.id.poiList);
mListView.addFooterView(mPageBar);
mAdapter = new PoiInfoAdapter(this, R.layout.poi_result_item, mAdapterItems);
mListView.setAdapter(mAdapter);
}
}
但是我有两个问题:
1 pageView将永远不会显示。
然后我试图评论这一行
this.setVisibility(GONE); // set it unvisible when inited
然后显示页面栏,但是mInformationTextView
的文本仍然为空,并且启用了mPrevButton
(由于页面为1,因此应将其禁用)。
我叫postInvalidate();
设置页面信息后,为什么它不能按预期运行?
2即使pageView出现了,如何使mPrevButton
mNextButton
和mInformationTextView
中心对齐?
根据您提供的代码,您无需手动使视图层次结构的任何部分无效。 尽管您已经创建了一个自定义视图,但您仍然仅在修改现有视图属性(例如,可见性),并且当这些更改发生时,这些视图将使自身无效。
之所以看不到该视图,是因为您已将其添加为ListView
的页脚视图,但是尚未设置适配器。 使用ListView
,页眉/页脚将添加到您通过setAdapter()
提供的任何适配器实现中,并作为列表项内容的一部分进行绘制。 没有列表适配器(即使当前为空),也没有视图。 因此,始终的最佳做法是立即在列表上设置适配器并在列表数据更改时对其进行更新,而不是等待列表数据设置适配器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.