我有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
为什么是我的自定义布局没有膨胀?
答案 0 :(得分: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);
}
答案 1 :(得分:0)
在convertView == null
之外扩展自定义布局。因为,convertView通常会返回先前回收的视图,因此,您的自定义视图永远不会被夸大。