ImageView变量甚至在定义后返回null; Android的

时间:2012-06-30 18:37:05

标签: android

在我的程序中,我试图使用ImageView从文件中显示图像。我已声明ImageView与ImageView XML文件相关,并使用BitmapFactory将值设置为文件中的图像。毕竟,我仍然收到NullPointerException,因为ImageView变量显然仍然是null。如果您有任何想法或建议,请告诉我,谢谢!

这是我正在谈论的代码:

public void imageViewMethod(String file){
    Logger log = Logger.getLogger("com.example.myclass");

    try {

    File fileName = new File(root, file);
    if(fileName.exists()){
    String dirFileName = fileName.toString();
    Toast.makeText(getApplicationContext(), dirFileName, Toast.LENGTH_LONG).show();
    ImageView iv = (ImageView)findViewById(R.id.image);

    iv.setImageBitmap(BitmapFactory.decodeFile(dirFileName));
    super.setContentView(iv);
    }
    }catch(Exception e){
        Toast.makeText(getApplicationContext(), "Hit Exception", Toast.LENGTH_LONG).show();
        log.log(Level.SEVERE, "uncaught exception", e);
    }
}

以及相应的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 

android:layout_margin="5dp">
</ImageView>

4 个答案:

答案 0 :(得分:0)

您是否正确设置了contentView()?您似乎在错误的地方使用了super.setContentView(iv);setContentView(R.layout.imageviewLayout.xml)用于活动类的onCreate()

检查活动类中是否包含以下代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageviewLayout.xml);

HTH。

答案 1 :(得分:0)

看起来你没有在oncreate中设置ContentView,你必须在获取ImageView之前设置ContentView

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.correspondingXML);

答案 2 :(得分:0)

在设置内容视图之前,您无法获得imageview。

答案 3 :(得分:0)

如果要在Activity运行时更改布局,请尝试使用LayoutInflater:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.image_layout, null);
setContentView(view);

现在findViewById(R.id.image)可以使用。

相关问题