findViewbyId在自定义适配器中返回null
问题描述:
我想在自定义适配器中检索textView,但由于某种原因返回null。你们能解释为什么吗?我是Android的新手,并且卡在这里。我还附加了适配器正在连接的视图,其名为profile_listitem.xml并包含我想要的textView。findViewbyId在自定义适配器中返回null
谢谢
AdapterProfile.xml
public AdapterProfiles(Context context,ArrayList<Profile> profilesArray)
{
super(context, R.layout.profile_listitem, profilesArray);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Profile p= getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.profile_listitem , parent, false);
}
TextView textAppName=(TextView)convertView.findViewById(R.id.textViewApp);
ToggleButton appStatus =(ToggleButton)convertView.findViewById(R.id.toggleAppStatus);
if(convertView.findViewById(R.id.textViewApp)==null)
Log.d("Profile","Profile is null");
textAppName.setText(p.getName());
appStatus.setChecked(p.isActive());
return convertView;
}
profile_listitem.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/background"
android:textColor="@color/blue"
android:textSize="36dp"
android:id="@+id/textViewAppName"/>
<ToggleButton
android:layout_width="72dp"
android:layout_height="48dp"
android:layout_alignParentEnd="true"
android:textColor="@color/white"
android:background="@color/blue"
android:id="@+id/toggleAppStatus"/>
答
因为你已经使用
R.id.textViewApp
,而不是你在xml文件即
R.id.textViewAppName
的TextView textAppName =(TextView的)convertView.findViewById定义了什么( 'R.id.textViewApp');