简体   繁体   English

Android以编程方式更改imageview

[英]android change imageview programmatically

I am making an android app where the same imageview is displayed every time the user enters a value. 我正在制作一个Android应用,每次用户输入一个值时,该应用就会显示相同的imageview。 but I want the imageview to be changed every time the user enters a value. 但我希望每次用户输入一个值时都要更改imageview。 I wrote a code to do this but the problem is after the first image is displayed I face black screen and it takes me to the first page in the app, it doesn't crash just shows black screen. 我编写了一个代码来执行此操作,但是问题是在显示第一张图像后,我面对黑屏,它将我带到应用程序的第一页,它不会崩溃而只是显示黑屏。

here is the imageview code in xml file: 这是xml文件中的imageview代码:

    <ImageView
        android:id="@+id/ImageSuccess"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_marginBottom="20dip"
        android:layout_marginTop="20dip"
        android:scaleType="centerInside"
        android:src="@drawable/image1" />

and here where I changed the imageview in java file: 在这里我更改了java文件中的imageview:

  ImageView myImage= (ImageView) findViewById(R.id.ImageSuccess);    

   if(userVlue.equals("SCHOOL")){

        myImage.setImageResource(R.drawable.image1);    
    }
    else if(userVlue.equals("CAR")){
        myImage.setImageResource(R.drawable.image2);    
    }
   else if(userVlue.equals("TOY")){
       myImage.setImageResource(R.drawable.image3); 
    }

One of myImage or userVlue is not set properly and probably is null. myImage或userVlue之一未正确设置,可能为null。 Debug and share logs. 调试和共享日志。 Your partcular activity is getting distroyed probably because of nullpointexception hence returning to main activity in backtrack. 您的特定活动可能由于nullpointexception而受到破坏,因此回到了原路。

I tried with a sample app and your logic is working perfectly. 我尝试了一个示例应用程序,您的逻辑运行良好。

You are handling user action on some UI element, when you do findViewById, cotext is that UI element, so this method searches ImageSuccess in children of it. 您正在处理某些UI元素上的用户操作,当您执行findViewById时,cotext是该UI元素,因此此方法在其子元素中搜索ImageSuccess。 Try giving page layout as rootlayout and do rootlayout.findViewById("ImageSuccess"); 尝试将页面布局设置为rootlayout,然后执行rootlayout.findViewById(“ ImageSuccess”);

我终于找到了解决方案,因为图像仅在可绘制文件中而出现了黑屏,所以我需要在所有可绘制桥文件夹中添加图像,例如drawable-ldp,drawable-ldpi等。可以在不同尺寸的手机上使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM