Android 带子项的 ListView 导致 TwoLineListItem 无法转换为 android.widget.TextView

Android ListView with subitem causes TwoLineListItem cannot be cast to android.widget.TextView

我已经创建了一个可以显示项目和子项目列表的 ListView,遵循这个问题:android-listview-subitems

但是,当我单击其中一行时,出现错误:E/MessageQueue-JNI: java.lang.ClassCastException: android.widget.TwoLineListItem cannot be cast to android.widget.TextView

只有在我向 ListView 中的每个项目添加子项目后,错误才开始出现。

listView 的侦听器发生错误,代码如下:

   //listview listener
lvAppFeatures.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //find the selected item and store the value to send to next screen
        strSelectedFeature = ((TextView) view).getText().toString();

        //move to display screen
        Intent switchActivity = new Intent(MainActivity.this,
                NextActivity.class);

        startActivity(switchActivity);
    }
});

有没有办法在 ListView 中拥有一组项目和一个子项目,但打算打开另一个 activity 作品?

您似乎在使用 android.R.layout.simple_list_item_2

<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<TextView android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    style="?android:attr/listItemFirstLineStyle"/>

<TextView android:id="@android:id/text2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@android:id/text1"
    style="?android:attr/listItemSecondLineStyle" />

</TwoLineListItem> 

一个) 直接从适配器获取项目

 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    //find the selected item and store the value to send to next screen
    strSelectedFeature = (String)parent.getAdapter().getItem(position);

或 B),如果您想访问文本视图

 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    //find the selected item and store the value to send to next screen
    TextView textView1 = view.findViewById(android.R.id.text1);
    TextView textView2 = view.findViewById(android.R.id.text2);
    //do other things like textView1.getText() etc