【问题标题】:Null Pointer when set imageView with programatically以编程方式设置 imageView 宽度时的空指针
【发布时间】:2012-11-18 10:51:35
【问题描述】:

我正在膨胀 xml,我从这个 xml 创建视图。我需要修改图像的宽度,但出现 NullPointerException。

我的代码是:

for (int o = 0; o < study.size(); o++) {
     LayoutInflater li_est= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View vEst = li_est.inflate(R.layout.study_details, null);

 line = (ImageView)findViewById(R.id.img_line);

 if (getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE) {
      **// HERE NEED CHANGE WIDTH OF LINE BUT I GET THE EXCEPTION**
}

我尝试通过以下方式这样做:

 1.     line.getLayoutParams().width = 20;
 2.     line.setMaxWidth(20);
 3.     line.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

我认为问题来自通货膨胀,任何解决方案,谢谢你,我为我的英语不好表示歉意。

【问题讨论】:

    标签: android imageview width layout-inflater


    【解决方案1】:
     final View vEst = li_est.inflate(R.layout.study_details, null);
     line = (ImageView)vEst.findViewById(R.id.img_line);
    

    可能 line 是在 stud_details 布局内声明的,因此您需要 vEst 对象来检索它

    【讨论】:

    • 我确定这是我的问题。不明白我以前怎么看不到,谢谢!
    • 不客气。如果它解决了您的问题,请记住将答案标记为“已接受的答案”
    • 我将如何放置宽度 WRAP_CONTENT?我尝试line.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT; 并不起作用
    • LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); line.setLayoutParams(layoutParams);
    【解决方案2】:

    你必须在膨胀的视图上执行 findViewById()...所以这样做:

    最终视图 vEst = li_est.inflate(R.layout.study_details, null); line = (ImageView) vEst.findViewById(R.id.img_line);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2011-04-01
      • 2014-07-11
      • 2014-08-22
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多