【发布时间】:2014-05-27 03:52:30
【问题描述】:
我有一个线性布局的 ArrayList。每个 LinearLayout 都包含几个以编程方式添加的其他视图。
我想要做的是在 ListView 中显示这些 LinearLayout 视图,以便利用 ListView 的能力只呈现需要的内容。
我的原始代码使用了一个在布局 xml 中定义的 ScrollView,我以编程方式将我的每个 LinearLayouts 添加到 ScrollView 中,它运行良好。
我现在用 ListView 替换了 xml 中的 ScrollView,并添加了一个适配器。
在下面的示例中,我简化了所有尝试并找到问题的根源。当适配器的 getView 方法返回 LinearLayout 时,我得到一个 ClassCastException。
活动布局 xml (trend_scrollable.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ListView
android:id="@+id/trend_listview"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
每一行的布局(simple_chart_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/chartItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
适配器:
public class ChartArrayAdapter extends ArrayAdapter<LinearLayout>
{
ArrayList<LinearLayout> layoutList;
public ChartArrayAdapter(Context context, ArrayList<LinearLayout> list)
{
super(context, R.layout.simple_chart_item, list);
this.layoutList = new ArrayList<LinearLayout>(list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
return layoutList.get(position);
}
@Override
public int getCount()
{
return this.layoutList != null ? this.layoutList.size() : 0;
}
}
活动:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.trend_scrollable);
ListView layout = (ListView) findViewById(R.id.trend_listview);
ArrayList<LinearLayout> layoutList = new ArrayList<LinearLayout>();
for (int i = 0; i < 2; i++)
{
layoutList.add(getDemoView(GlobalVars.getContext(), i));
}
ChartArrayAdapter adapter = new ChartArrayAdapter(this, layoutList);
layout.setAdapter(adapter);
}
有人可以帮我解决这个问题吗?我已经简化了适配器的 getView 方法,总是只返回一个 LinearLayout 视图,我认为这意味着总是会创建一个新视图。我怀疑返回的 LinearView 可能有问题并将其与“simple_chart_layout.xml”匹配,也许..
【问题讨论】:
-
这个线程中的答案有一个很好的自定义列表视图的完整示例:stackoverflow.com/questions/23512344/…
标签: java android listview adapter