根据位置膨胀ListView中自定义视图(Inflating custom View in List

2019-10-28 10:31发布

我有一个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

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

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


Answer 2:

充气外的自定义布局convertView == null 。 因为,convertView通常会返回先前回收的观点,因此,您的自定义视图永远不会被夸大。



文章来源: Inflating custom View in ListView according to position