我正在构建一个自定义视图,有点像自定义条形图。我正在扩展这个LinearLayout
。然后,自定义视图会从数据填充视图。问题是,每当我希望视图"刷新"时,我都会调用removeAllViews()
和类似的方法,因此自定义视图布局是干净的,然后要重新填充数据,我调用addView()
,但子视图不显示。我需要调用removeAllViews
的原因是子视图不会在自定义视图中重复。
这些是我的自定义视图中的一些片段,我也实现了onLayout()
因此每当我显示自定义视图时,我都会获得适当的高度以进行布局。 BarChartData
只是应在此自定义视图中显示的数据的模型类:
public void setChartData(BarChartData data) {
this.chartData = data;
addBarDataToUi();
}
void addBarDataToUi() {
Log.d(TAG, "Add bar data to UI called");
if (chartData != null) {
//this.removeAllViews(); -> first one I tried, no luck, not displaying views after `addView`
//this.removeAllViewsInLayout(); -> tried this too but no luck
this.removeViewsInLayout(0, this.getChildCount()); // again, to no avail :(
for (int i = 0, count = chartData.getItemCount(); i < count; i++) {
addBarItemDataUi(chartData.getItemByPos(i));
}
Log.d(TAG, "Child count: " + this.getChildCount());
}
}
void addBarItemDataUi(BarItemData data) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.bar_chart_item, this, false);
FrameLayout mainLayout = (FrameLayout) layout.findViewById(R.id.bar_chart_item_main_layout);
//TextView topText = new TextView(getContext());
TextView topText = (TextView) layout.findViewById(R.id.bar_chart_item_top_text);
TextView bottomText = (TextView) layout.findViewById(R.id.bar_chart_item_bottom_text);
topText.setText(String.valueOf(data.percentage));
bottomText.setText(data.title);
mainLayout.setBackgroundColor(data.backgroundColor);
Log.d(TAG, "Height: " + this.getMeasuredHeight() + ", Top text height: " + topText.getMeasuredHeight());
int heightRel = (int) (data.getPercentageFractal() * (double) this.getMeasuredHeight());
mainLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, heightRel));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
params.gravity = Gravity.BOTTOM;
layout.setLayoutParams(params);
this.addView(layout);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
Log.d(TAG, "On layout..");
if (chartData != null) {
addBarDataToUi();
}
}
好吧,我已经搜索了这个问题,出现的很少,几乎相同的场景和问题,但我认为他们在删除AllViews后还没有解决有关addView的问题。
我猜通过在addBarDataToUi()
内部调用removeAllViews()
函数,当函数被调用时onLayout()
setChartData(BarChartData data)
它会添加子视图,从而触发onLayout()
函数,该函数调用addBarDataToUi()
并在某种常量循环中删除视图等。安卓文档说
避免在
onDraw()
或任何相关功能中使用removeAllViews()
http://developer.android.com/reference/android/view/ViewGroup.html#removeAllViews()
我假设这可能还包括 onLayout() 函数。
我最好的建议是在调用setChartData(BarChartData data)
函数之前将removeAllViews()
函数调用移动到addBarDataToUi()
希望对你有帮助