1

我在使用LayoutInflater来膨胀父级布局后,在ImageView上的NullReferenceExcpetion时出现了一些问题。正如你可以在下面的布局XML中看到的,我有两个TextView和一个ImageView。我可以很好地引用两个TextView,但不是ImageView。ImageView在膨胀的LinearLayout上抛出NullReferenceException

当我钻到到的胖布局的子视图属性,我看到,无论是TextViews的中期财产是正确的,但是的ImageView的中期是-1

会有人有任何想法为什么只有ImageView会成为NULL?我相信这是愚蠢的,但我无法弄清楚。我也重新创建了布局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"); 
+0

我打算建议您清理并重建您的项目。然后我发现你说你“清理了我的解决方案”。如果这并不意味着同样的事情,那么请尝试清理并重建您的项目。 – 2011-06-01 03:48:27

+0

是的,我的意思是项目。我已经更新了这个问题,谢谢你的支持。 – hooked82 2011-06-01 03:53:33

回答

1

我以某种方式得到了这个工作。我正在回答我自己的问题,因为这个问题已经通过其他解决方案解决了,但Jaydeep和CapDroid的答案都能正确地工作以扩大视图。

在尝试多种不同的方式来充气我的视图后,我第三次重新创建了布局XML文件,更改了ID并重新清理了项目。不知何故,在这个过程中,我的问题消失了,所以我被引导认为这是我的设置或系统的问题。

感谢所有提供帮助和指导的人!

0

试试这个...

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)); 
+0

尝试两个代码示例时,我会得到相同的结果。 ImageView仍然为空。 – hooked82 2011-06-01 06:11:58

+0

检查您的布局名称.. – 2011-06-01 06:17:44

+0

请参阅我的更新回答 – 2011-06-01 06:29:37

0

试试这个代码:

String inflater = Context.LAYOUT_INFLATER_SERVICE; 
    LayoutInflater li = (LayoutInflater)ctx.getSystemService(inflater); 
    v = li.inflate(R.layout.icon, null); 
相关问题