我正在尝试获取一个程序,让用户导入自定义背景。

我在这里:

我有将另一个函数作为参数的getDrawable函数:

mDrawableBg = getResources().getDrawable(getImage());


getImage()假定返回一个引用所选图像的整数,这是该函数的代码(到目前为止):

public int getImage(){

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 10);

}


假设这是要打开图库并让用户选择图像。然后,我将使用mDrawableBg设置背景。我不确定如何将参考ID返回到该所选图像。有什么建议么?

最佳答案

恐怕您尝试执行此操作的方式是不可能的。作为新的Android开发人员,您要学习的一件事是活动之间的周期如何工作。在您的情况下,您正在运行Activity,该Intent调用Intent从中获取数据。但是,在Android API中,只能在自己的时间引用getImage()。这意味着您不能使用尝试的方法使用Intent方法。

虽然有希望!

您首先需要做的就是调用getImage()。您将通过现在在getImage()中的代码来完成此操作:

public void getImage() { // This has to be a void!
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 10);
}


现在,此方法将启动您要用户选择的图像选择器。接下来,您必须了解返回的内容。不能从您的mDrawableBg = getResources().getDrawable(getImage());方法返回该值,而是必须从其他位置收集它。

您必须实现以下方法:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        final int SELECT_PICTURE = 1; // Hardcoded from API
        if (requestCode == SELECT_PICTURE) {
            String pathToImage = data.getData().getPath(); // Get path to image, returned by the image picker Intent
            mDrawableBg = Drawable.createFromPath(pathToImage); // Get a Drawable from the path
        }
    }
}


最后,只需调用getImage();,而不是调用Activity。这将初始化图像选择器。

一些阅读:


Android Intent (notably stuff about Drawables and getting a result back)
Android Drawable
Getting a Intent from a path
More on the Image Picker


祝好运!

09-11 18:51
查看更多