ImageView在膨胀的LinearLayout上抛出NullReferenceException

|| 使用LayoutInflater填充父级布局后,ImageView上的NullReferenceExcpetion出现了一些问题。正如您在下面的布局XML中看到的那样,我有两个TextView和一个ImageView。我可以很好地引用两个TextView,但不能引用ImageView。 当我深入查看展开的布局的子视图的属性时,我看到两个TextView的mID属性都是正确的,但是ImageView的mID为-1 会有人知道为什么只有ImageView会显示为NULL吗?我确定这有点愚蠢,但我无法弄清楚。我还重新创建了Layout XML文件,清理了我的项目,等等。 提前致谢!! 布局XML:
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout
  xmlns:android=\"http://schemas.android.com/apk/res/android\"
  android:layout_width=\"wrap_content\"
  android:layout_height=\"wrap_content\"
  android:orientation=\"vertical\">
    <LinearLayout android:layout_width=\"120px\"
                  android:layout_height=\"wrap_content\"
                  android:orientation=\"vertical\">
        <TextView android:id=\"@+id/weather_forecast_day\"
                  android:layout_width=\"wrap_content\"
                  android:layout_height=\"wrap_content\"
                  android:layout_gravity=\"center_horizontal\"
                  android:textStyle=\"bold\"/>
        <ImageView android:id=\"@+id/weather_forecast_icon\"
                   android:layout_width=\"wrap_content\"
                   android:layout_height=\"wrap_content\"
                   android:layout_gravity=\"center_horizontal\"/>
        <TextView android:id=\"@+id/weather_forecast_temps\"
                  android:layout_width=\"wrap_content\"
                  android:layout_height=\"wrap_content\"
                  android:layout_gravity=\"center_horizontal\"
                  android:textStyle=\"bold\"/>
    </LinearLayout>
</LinearLayout>
码:
mForecastItem = (LinearLayout)View.inflate(WeatherLookup.this, R.layout.weather_forecast_item, null);

((ImageView)mForecastItem.findViewById(R.id.weather_forecast_icon))
                 .setImageDrawable(getResources().getDrawable(R.drawable.weather_sunny));
((TextView)mForecastItem.findViewById(R.id.weather_forecast_day))
                .setText(forecast.DayOfWeek);
((TextView)mForecastItem.findViewById(R.id.weather_forecast_temps))
            .setText(forecast.High + \"\\u2109 / \" + forecast.Low + \"\\u2109\");
    
已邀请:
        我以某种方式使它起作用。我正在回答我自己的问题,原因是该问题已通过随后提供解决方案的其他方式解决了,但是Jaydeep和CapDroid的回答都可以正常工作以扩大视图。 在尝试以多种方式显示视图后,我第三次重新创建了Layout XML文件,更改了ID,然后重新清理了Project。在这个过程中,我的问题以某种方式消失了,所以我被认为是我的安装程序或系统都有问题。 感谢所有提供帮助和指导的人!     
        试试这个代码:
String inflater = Context.LAYOUT_INFLATER_SERVICE;
    LayoutInflater li = (LayoutInflater)ctx.getSystemService(inflater);
    v = li.inflate(R.layout.icon, null);
    
        尝试这个...
LayoutInflater inflater;
inflater = activity.getLayoutInflater();
mForecastItem = (LinearLayout)inflater.inflate(
                R.layout.weather_forecast_item, null);



((ImageView)mForecastItem.findViewById(R.id.weather_forecast_icon))
                 .setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.weather_sunny));
    

要回复问题请先登录注册