问题描述
activity_mail.xlm:
from mymodule import myfunc
...和listitem_device.xlm:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/results"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/profilesCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="18sp" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/device_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>
<TextView
android:id="@+id/device_service"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"/>
</LinearLayout>
问题是随后的代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
@Override
public View getView(int i,View view,ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device,null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_label); // from listitem_device.xml
viewHolder.profilesCount = (TextView) view.findViewById(R.id.profilesCount); // from activity_main.xml
生成错误“尝试在空对象引用上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'”。
我该如何解决?
解决方法
我在任何地方都看不到ID为“ profilesCount”的视图。布局文件中只有设备标签和设备服务作为ID,您可以使用该文件来充气列表视图的行。也可以使用Recycler视图,它提供了更大的灵活性。
此外,您无法在适配器的getView()函数中访问来自activity_mail.xml的内容,因为通过在getfunction中使用“视图”,因为该视图仅对应于列表视图的行,并且由于该id不对应如果与列表视图的行相关联的xml文件中存在该字符串,则将“ viewholders.profileCount”设置为null,因此会出现Nullpointer异常。
如果要在适配器中使用TextView或任何视图,最好在活动中创建一个接口并实现该接口以用作回调,然后设置activity.xml文件的textview字段,这是最好的方法其他方法是将活动的引用传递给适配器,然后从actvity_mail.xml文件中找到文本视图或您要使用的任何内容,但不建议这样做,这是非常糟糕的方法可能需要更多内存。