0

我有一个ListView我想View在某个位置为自定义充气的地方。它实际上是第 11 项(位置 10)。

getCount()方法返回 11。

这是该getView()方法的顶部:

public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    if (convertView == null) {              
        if (position < 10) {
            convertView = mInflater.inflate(R.layout.standard, null);           
        } else {
            convertView = mInflater.inflate(R.layout.custom, null);
            Log.i(TAG, "Inflated custom layout");
        }
        Log.i(TAG, "getView, position = "+position);
        holder = new ViewHolder();
        holder.tv = (TextView) convertView.findViewById(R.id.tv);
        holder.radioButton = (RadioButton) convertView.findViewById(R.id.radioButton1);             
        convertView.setTag(holder);             
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    ...
    Log.i(TAG, "getView() : position = " + position);
}

这是我在 logcat 中看到的:

getView, position = 0
getView, position = 1
getView, position = 2

其余的 getView 日志不显示;我会假设这条线会一直出现到getView, position = 10.

而这一行:convertView = mInflater.inflate(R.layout.custom, null);永远不会被调用,因为Inflated custom layout不会出现在 logcat 中。

不过这很有趣,因为底部的 logcat 总是被调用(当我向下滚动时ListView):

getView() : position = 0
getView() : position = 1
getView() : position = 2
getView() : position = 3
getView() : position = 4
getView() : position = 5
getView() : position = 6
getView() : position = 7
getView() : position = 8
getView() : position = 9
getView() : position = 10

为什么我的自定义布局没有膨胀?

4

2 回答 2

1

getView()当方法View convertView不为空时,您需要扩展布局。View从中返回的将getView()被重复使用。如果您检查视图是否为空并膨胀,它只会在第一次返回时膨胀View

public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    if (convertView == null) {              
        if (position < 10) {
            convertView = mInflater.inflate(R.layout.standard, null);           
        }
        Log.i(TAG, "getView, position = "+position);
        holder = new ViewHolder();
        holder.tv = (TextView) convertView.findViewById(R.id.tv);
        holder.radioButton = (RadioButton) convertView.findViewById(R.id.radioButton1);             
        convertView.setTag(holder);             
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    ...

    if(position > 10) {
         convertView = mInflater.inflate(R.layout.custom, null);
         Log.i(TAG, "Inflated custom layout");
    }

    Log.i(TAG, "getView() : position = " + position);
}
于 2013-04-19T06:58:52.787 回答
0

在外部膨胀自定义布局convertView == null。因为,convertView 通常会返回以前回收的视图,因此您的自定义视图永远不会膨胀。

于 2013-04-19T07:03:50.827 回答