我正在尝试创建自己的列表,因此我正在扩展AdapterView类。 我重写了onLayout方法来添加子项,测量它们并调用布局方法。 我的问题是onLayout方法被无限调用,每次调用都会重复项目。 我已经在互联网上查看并确认我的孩子没有改变(我让每个孩子都返回一个没有动态内容的空视图)。 这是我的代码:
protected void onLayout(final boolean changed, final int left, final int top, final int right,
final int bottom)
{
super.onLayout(changed, left, top, right, bottom);
// If we don't have an adapter yet, do nothing and return
if(mAdapter == null)
{
return;
}
fillList();
positionItems();
}
fillList():
private void fillList()
{
int position = 0;
if(mCurrentList*mNumberItemsPerList > mAdapter.getCount() )
{
mCurrentList= 0;
return ;
}
if(mCurrentList < 0)
{
double lastList = (double)(mAdapter.getCount()/mNumberItemsPerList);
mCurrentList= (int) Math.ceil(lastList);
return ;
}
//this.removeAllViewsInLayout();
while( position+mCurrentList*mNumberItemsPerList < mAdapter.getCount() )
{
// Child view
final View child = mAdapter.getView(position+mCurrentList*mNumberItemsPerList, null, this);
// Add the child and measure its dimensions to calculate the remaining space
addAndMeasureChild(child);
position++;
}
}
addAndMeasureChild():
private void addAndMeasureChild(View child)
{
LayoutParams params = child.getLayoutParams();
if(params == null)
{
params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
}
//child.setLayoutParams(params);
addViewInLayout(child,-1, params);
// measure the dimensions
child.measure(MeasureSpec.EXACTLY | 250,MeasureSpec.EXACTLY | 250);
}
positionItems():
private void positionItems()
{
int left = 0;
int middleItem = mNumberItemsPerList / 2;
for(int index =0; index < getChildCount(); index++)
{
View child = getChildAt(index);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
int bottom= (getHeight()-height)/2;
if(index < middleItem)
{
child.layout(left+15, 70+(middleItem-index)*30, left+width, 70+(middleItem-index)*30+height);
}
if(index == middleItem)
{
child.layout(left+15, 70, left+width, 70+height);
}
if(index > middleItem)
{
int diff = index -middleItem;
child.layout(left+15, 70+(middleItem-(index - (middleItem*diff)))*30, left+width, 70+(middleItem-(index - (middleItem*diff)))*30+height);
}
left += width;
}
}
这是我孩子的getView:
public View getView(final int position, final View convertView, final ViewGroup parent)
{
View view = convertView;
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.cat_item_layout, null);
}
return view;
}
答案 0 :(得分:0)
我已经弄明白是什么导致对onLayout的无限调用。 在我的主要布局上,我在相对布局中添加了一个带有此自定义视图的时钟。 我不知道为什么但是时钟(每秒更新一次)会导致我的视图再次调用onLayout。