在List中组合imageView和TextView

时间:2013-05-09 09:12:53

标签: android android-listview

您好我正在开发一个Android应用程序,我使用扩展BaseExpandableListAdapter的子类。现在我有问题在显示的列表中合并ImageViewTextView。昨天我发现stackoverflow上的这个链接帮助我完成了这个组合。

Overlay text over imageview in framelayout programmatically - Android

所以它很有效! - 直到我点击listItem。应用程序chrash和logcat告诉我 "android.widget.RelativeLayout" cannot be cast to android.widget.ImageView.此异常来自扩展getGroupView()的类中的BaseExpandableListAdapter。为什么会这样? (RelativeLayout扩展View)。

当我尝试返回RelativeLayout而不是ImageView时,我是否完全走错了路?

这是我getGroupView的代码(因为我在一个测试状态,我有点乱):

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

  ImageView row = (ImageView) convertView;

RelativeLayout rLayout = new RelativeLayout(mContext);
  LayoutParams rlParams = new LayoutParams(LayoutParams.FILL_PARENT
            ,LayoutParams.FILL_PARENT); 
    rLayout.setLayoutParams(rlParams);


if(row == null) {

    row = new ImageView(mContext);
}

row.setImageResource(R.drawable.ic_launcher);

row.setScaleType(ImageView.ScaleType.FIT_START);


RelativeLayout.LayoutParams tParams = new RelativeLayout.LayoutParams
        (LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
tParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
tParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
TextView text=new TextView(mContext); 
text.setText("GOLDEN Gate"); 
text.setTextColor(Color.WHITE);                            
text.setTypeface(Typeface.DEFAULT_BOLD);
text.setLayoutParams(tParams);



rLayout.addView(row);
rLayout.addView(text);

return rLayout;
}

1 个答案:

答案 0 :(得分:0)

声明ImageView row = (ImageView) convertView;提供了异常,因为您试图将RelativeLayout转换为ImageView

您必须在convertView方法中返回getViewGroup(),但您要返回RelativeLayout,即return rLayout;

解决方案:

ImageView内添加TextViewRelativeLayout。通过在getView()方法中对其进行膨胀来设置ListItem的布局,并将膨胀的布局分配给convertView。在getView()方法中返回convertView;