ConstraintLayout无法强制转换为android.widget.TextView

问题描述 投票:0回答:1

我尝试启动活动时遇到运行时错误。

发生错误的行:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

        textView1.setText("Csatlakozás...");
        String info = ((TextView) v).getText().toString(); // <-- ERROR HERE
        String address = info.substring(info.length() - 17);
        Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
        i.putExtra(EXTRA_DEVICE_ADDRESS, address);
        startActivity(i);
    }
};

logcat的:

java.lang.ClassCastException:android.support.constraint.ConstraintLayout无法转换为arduinosensors.example.com.smarthome3.DeviceListActivity $ 1.onItemClick(DeviceListActivity.java:106)中的android.widget.TextView

这里发生了什么?在我开始使用具有自定义行布局的自定义数组适配器之前,这很好。

编辑:

custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

我的适配器:

public class UsersAdapter extends ArrayAdapter<Adapter> {
    public UsersAdapter(Context context, ArrayList<Adapter> users) {
        super(context, 0, users);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Adapter user = getItem(position);

        if (convertView == null) {
            LayoutInflater sontInflater = LayoutInflater.from(getContext());
            convertView = sontInflater.inflate(R.layout.custom_row,parent,false);
        }

        TextView one = (TextView) convertView.findViewById(R.id.textView);
        TextView two = (TextView) convertView.findViewById(R.id.textView2);

        one.setText(user.name);
        two.setText(user.hometown);

        return convertView;
    }
}
java android casting adapter
1个回答
1
投票

来自documentation

视图:已单击的AdapterView中的视图(这将是适配器提供的视图)

在你的情况下,View是根ConstraintLayout。并且因为错误说你不能把它投到TextView。要获得您可以使用的信息:

String info = v.findViewById(R.id.textView).getText().toString()

© www.soinside.com 2019 - 2024. All rights reserved.