我已经在 webview 中打开了 html 页面。现在单击 webview 中的任何按钮,我希望用户从图库中选择图像并在 webview 中显示该图像。
onCreate() 方法中的代码:
myBrowser = (WebView)findViewById(R.id.webView1);
final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/mypage.html");
添加了javascript接口:
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void pickImageFromGallery()
{
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
}
onActivityResult() 方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = 4;
Bitmap image = BitmapFactory.decodeFile(picturePath, o2);
}
}
现在,每当我单击 webview 中的按钮时,它都会打开图库并让用户从图库中选择图像。但是我怎样才能将该图像路径再次发送到 javascript,以便它可以在 webview 中显示该图像?