如何获取有关Android Image按钮的此代码才能正常运行

时间:2013-07-30 01:58:00

标签: android gallery imagebutton

好的,所以我在这个网站上查看了各种答案,在实践中它们看起来都很棒,而且几乎是标准的做法。嗯,标准失败了我。所以,我希望让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;
    }


}

请帮助我现在真的让我感到紧张哈哈...

2 个答案:

答案 0 :(得分:0)

使用此代码。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 1:
     {
      if (resultCode == RESULT_OK)
      {
       if(requestCode == 1)
        {
         Uri photoUri = data.getData();
         if (photoUri != null)
         {
          try {
              String[] filePathColumn = {MediaStore.Images.Media.DATA};
              Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
              cursor.moveToFirst();
              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
              String filePath = cursor.getString(columnIndex);
              cursor.close();
              bMap_image = BitmapFactory.decodeFile(filePath);
              wrestlerPicture.setImageResource.setImageBitmap(bMap_image);


     }catch(Exception e)
      {}
      }
    }
    }
  }
}

答案 1 :(得分:0)

(1)不要说“这真的让我感到紧张”然后“哈哈......”它让我觉得你'脸上露出满脸的笑容,背后还有一把刀。

(2) cursor.moveToFirst() 返回布尔值,所以:

if(cursor.moveToFirst())
   Log.d("CURSOR STATUS: ", "SUCCESSFULLY MOVED TO FIRST");
else
   Log.d("CURSOR STATUS: ", "FAILED TO MOVE TO FIRST :'(");

(3)这次印刷是什么?

System.out.println("Image Path : " + selectedImagePath);

如果它正在打印实际的uri路径,这有助于很多。但是你应该使用Logcat,而不是System。

(4)我在自己的应用程序中做了类似的事情,但我正在改变一个imageview。也许代码会有用:

Uri selectedImageUri = data.getData();
                //In the following code, I'm trying to get 
                //the path for the image file 
                try {
                    imageBMP = null;
                    String selectedImagePath = getPath(selectedImageUri);
                    if (selectedImagePath != null) {
                        filePath = selectedImagePath;
                        //Potentially long-running tasks must be put on their own
                        //thread.
                        Thread DecodeRunnable = new Thread(new Runnable(){
                            public void run() {
                                    decodeFile();
                            }
                        });             
                        DecodeRunnable.start();
                    }
                 }//try

这是decodeFile()方法:

    public void decodeFile() {
    //This method decodes the file from base 64 to base 32,
    //which allows us to manipulate it as a bitmap in android.

    BitmapFactory.Options o = new BitmapFactory.Options();
        //This option lets us create a bitmap without the extra
        //overhead of allocating new memory for data on its pixels
    o.inJustDecodeBounds = true;

        //If you see this error, then darkness has befallen us.
    if(BitmapFactory.decodeFile(filePath, o) == null){
        Log.d("DECODING: ", "Error! The file is null in the decoding code!");
    }

    BitmapFactory.Options o2 = new BitmapFactory.Options();
        //This option will scale the file. There's no need to get the full-sized
        //image, since it could crash the app if its size exceeds the memory in
        //the heap (It's Java's fault, not mine.)
    o2.inSampleSize = 2;
    imageBMP = BitmapFactory.decodeFile(filePath, o2);

        //The following code will set the image view that the user sees. That
        //has to be run on the ui thread.
    runOnUiThread(new Runnable(){
        public void run(){
            if (imageBMP != null) {
                Bitmap imageViewBMP = null;
                    //Scale the image if necessary so it doesn't fill the entire
                    //app view, which it will do if it's big enough.
                if(imageBMP.getWidth() > 175 && imageBMP.getHeight() > 200){
                    imageViewBMP = Bitmap.createScaledBitmap(imageBMP, 200, 200, 
                            true);
                }
                else{
                    imageViewBMP = imageBMP;
                }
                imageViewIV.setImageBitmap(imageViewBMP);
            }//if(imageBMP != null)
            else{
                Resources res = getResources();
                imageViewIV.setImageDrawable( res.getDrawable(R.drawable.noimage) );
                photoStatusTV.setText(R.string.no_photo_text);
                Toast.makeText(getApplicationContext(), "No image found.", 
                        Toast.LENGTH_LONG).show();
            }
        }
    });

}//decodeFile()

应该适合你。使用asynctasks可能比我使用的线程更好,但是这样更容易阅读。