好的,所以我浏览了这个网站上的各种答案,实际上它们看起来都很棒,而且几乎是这样做的标准方式。好吧,标准让我失望了。所以,我想让 ImageButton 访问图库并让用户选择图像。用户选择该图像后,我希望它成为 ImageButton 的背景。到目前为止,我的代码是:
package ion.takedown;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
public class newWrestler extends Activity {
private String selectedImagePath;
private ImageButton wrestlerPicture;
@Override
protected void onCreate(Bundle newWrestler) {
super.onCreate(newWrestler);
setContentView(R.layout.new_wrestler);
wrestlerPicture = (ImageButton) findViewById(R.id.wrestlerPhoto);
wrestlerPicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
wrestlerPicture.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
请帮帮我,现在真的让我很紧张哈哈......