如题,当ListView存在于ScrollView或者ListView里面时,会出现一种奇怪的现象,无法伸展,一直处于只能显示第一条item的状态。为了搞清楚这个问题,纠结了好久,最后终于在stackoverflow上找到了答案。
ListView并没有一个选项,能使之完全伸展开来。所以在ScrollView或者ListView中使用ListView is not a good idea。
我们可以使用LinearLayout实现类似的效果。写了一个自定义类,如下,可代替ListView,运用于ScrollView或者ListView。效果近视,可修改代码自定义。
package com.example.view;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class UnscrollableListView extends LinearLayout {
private Context context;
public UnscrollableListView(Context co) {
super(co);
context = co;
}
public UnscrollableListView(Context co, AttributeSet as)
{
super(co, as);
context = co;
}
public void setViews(Context co, List<Map<String, Object>> data,
int resource, String[] keys, int[] ids)
{
View view;
for (Map<String, Object> m : data)
{
view = LayoutInflater.from(co).inflate(resource, null);
bindView(view, m, keys, ids);
addView(view);
addView(getSeparator());
}
}
private View getSeparator()
{
View view;
view = new View(context);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
view.setBackgroundColor(getResources().getColor(R.color.separator));
return view;
}
private void bindView(View page, Map<String, Object>data, String[] keys, int[] ids)
{
View view;
Object obj;
for (int i = 0; i < keys.length; i++)
{
view = page.findViewById(ids[ i ]);
obj = data.get(keys[i]);
if (view instanceof TextView)
{
((TextView)view).setText(obj.toString());
} else if (view instanceof ImageView)
{
((ImageView)view).setImageResource((Integer)obj);
}
}
}
}