我可以在android中充气自定义视图吗?

时间:2014-11-14 16:59:13

标签: android android-layout android-listview android-view android-custom-view

我有自定义视图BananaPhoneView extends LinearLayout,我想将其显示在ListView

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    BananaPhoneView bananaPhoneView;
    if (convertView == null) {
        bananaPhoneView = (BananaPhoneView) LayoutInflater.from(context)
          .inflate(R.layout.banana_phone, parent, false);
    } else {
        bananaPhoneView = (BananaPhoneView) convertView;
    }

    BananaPhone bananaPhone = getItem(position);

    bananaPhoneView.update(bananaPhone);

    return bananaPhoneView;
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight">

    <TextView
        style="@style/BananaListItemTextView.Wide"
        android:text="Medium Text"
        android:id="@+id/text_view_banana_list_name" />

    <TextView
        style="@style/BananaListItemTextView.Wide"
        android:text="Medium Text"
        android:id="@+id/text_view_banana_list_address" />

    <TextView
        style="@style/BananaListItemTextView.Wide"
        android:text="Medium Text"
        android:id="@+id/text_view_banana_list_city" />

    <TextView
        style="@style/BananaListItemTextView.Narrow"
        android:text="x"
        android:id="@+id/text_view_banana_list_brand" />

</LinearLayout>

但是我得到了:

java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to com.example.banana.BananaPhoneView

有没有办法做到这一点?

我使用了本教程:http://www.piwai.info/android-adapter-good-practices/

1 个答案:

答案 0 :(得分:1)

我想这个

<LinearLayout xmlns:...

应该是这样的

<your.package.name.BananaPhoneView xmlns:...