[英]java.lang.ClassCastException: android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView
[英]ConstraintLayout cannot be cast to android.widget.TextView
當我嘗試啟動活動時,我不斷收到運行時錯誤。
發生錯誤的行:
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);
}
};
日志貓:
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;
}
}
從文檔:
View:被點擊的 AdapterView 中的視圖(這將是適配器提供的視圖)
在您的情況下, View
是根ConstraintLayout
。 正如錯誤所說,您無法將其轉換為TextView
。 要獲取信息,您可以使用:
String info = v.findViewById(R.id.textView).getText().toString()
您只是為您的約束布局弄錯了 id,並將其與您在 MainActivity 中進行聲明的 textview 混為一談
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.