Java ConstraintLayout无法强制转换为android.widget.TextView
当我尝试启动一个活动时,我总是遇到运行时错误 发生错误的行:Java ConstraintLayout无法强制转换为android.widget.TextView,java,android,casting,adapter,Java,Android,Casting,Adapter,当我尝试启动一个活动时,我总是遇到运行时错误 发生错误的行: private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { textView1.setText("Csatlakozás..."); St
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);
}
};
private-OnItemClickListener-mDeviceClickListener=new-OnItemClickListener(){
公共链接(AdapterView av、视图v、内部arg2、长arg3){
textView1.setText(“Csatlakozás…”);
字符串信息=((TextView)v).getText().toString();//来自:
视图:在AdapterView中单击的视图(这将是一个
(适配器提供的视图)
在您的情况下,视图
是根ConstraintLayout
。错误表明您无法将其转换为TextView
。要获取信息,您可以使用:
String info=v.findviewbyd(R.id.textView).getText().toString()
您刚为约束布局获得了错误的id,并将其与您在MainActivity中声明的textview混淆了您清理并重建了吗?@tyczj是的,没有发布更多代码以更好地理解我已经添加了相关代码,但是还有一个完整项目的链接。运行良好,谢谢!无论如何getText()这里不工作也许你需要把它放到TextView
是的,我想出来了,谢谢,你们真的很有帮助!
<?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;
}
}