android:在emply imageview中努力获得一个可绘制的工作

bf1o4zei  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(334)

android上的java:我试图在一个空的imageview中输入一个drawable,但它就是不起作用。我在“如果”下试过的任何东西都不起作用。抱歉,如果这听起来真的很愚蠢,我已经在这太久了(这是学校的工作)。
当我尝试运行模拟器时,我得到错误“name\u of \u 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();
    }
}
yws3nbqq

yws3nbqq1#

似乎您没有初始化imageview ivRobot ,所以我猜你得到了一个 NullPointerException 当你打电话的时候 ImageView::setImageDrawable .
尝试初始化 ImageView 这样地:

@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]);
        }
    }

相关问题