简体   繁体   中英

Android: Struggling to get a Drawable working in an emply ImageView

Java on Android: I am trying to input a Drawable into an empty ImageView but it just does not work. Literally anything I tried under the "if"'s is not working. Sorry if this sounds really stupid I've been at this for way too long (It's school work).

When I try to run the Emulator I get the Error "Name_of_project keep stop"

public class Robot extends AppCompatActivity {
    Boolean info;
    private ImageView ivRobot;
    Drawable[] imgs = new Drawable[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot);
        Intent RobotI = getIntent();
        info = RobotI.getBooleanExtra("info", false);
        imgs[0]=ResourcesCompat.getDrawable(getResources(),R.drawable.robot,null);
        imgs[1]=ResourcesCompat.getDrawable(getResources(),R.drawable.notarobot,null);
        if (info==true) {
            ivRobot.setImageDrawable(imgs[0]);
        }
        else if (info==false) {
            ivRobot.setImageDrawable(imgs[1]);
        }
    }

    public void GoBack() {
        Intent Main = new Intent(this, MainActivity.class);
        startActivity(Main);
    }

    public void btnGoBack(View view) {
        GoBack();
    }
}

It seems like you didn't initialize your ImageView ivRobot , so I guess you're getting a NullPointerException when you call ImageView::setImageDrawable .

Try initialize your ImageView like this:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot);
        Intent RobotI = getIntent();
        info = RobotI.getBooleanExtra("info", false);

        // todo: put your ImageView id
        ivRobot = findViewById<ImageView>(R.id.iv_robot)

        imgs[0]=ResourcesCompat.getDrawable(getResources(),R.drawable.robot,null);
        imgs[1]=ResourcesCompat.getDrawable(getResources(),R.drawable.notarobot,null);
        if (info) {
            ivRobot.setImageDrawable(imgs[0]);
        }
        else {
            ivRobot.setImageDrawable(imgs[1]);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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