2015-10-03 48 views
0

我確定在某處有答案,但我似乎無法找到任何東西。 我試圖做到這一點,當用戶點擊應用程序菜單上的項目時,它將開始意圖到手機的畫廊選擇他們選擇的圖像來更改應用程序的背景,而不是預先設置的背景圖像。有沒有辦法做到這一點。如何從手機圖庫中設置應用程序背景

這是我有什麼代碼,但是當我在手機上運行它時,應用程序崩潰。

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    Intent sendIntent = null; 
    if (id == R.id.action_settings) { 


     sendIntent = new Intent(); 
     sendIntent.setAction(Intent.ACTION_SEND); 
     sendIntent.putExtra(Intent.EXTRA_TEXT, "Try Out this new app..."); 
     sendIntent.setType("text/plain"); 
     startActivity(sendIntent); 
    } 


    PackageManager packageManager = getPackageManager(); 
    List<ResolveInfo> activities =     packageManager.queryIntentActivities(sendIntent, 0); 
    boolean isIntentSafe = activities.size() > 0; 


    String title = getResources().getString(R.string.chooser_title); 

    Intent chooser = Intent.createChooser(sendIntent, title); 


    if (sendIntent.resolveActivity(getPackageManager()) != null) { 
     startActivity(chooser); 
    } 



    //noinspection SimplifiableIfStatement 

    if (id == R.id.change_background){ 
    Intent pictureIntent = new Intent(); 
    pictureIntent.setType("image/*"); 
    pictureIntent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(pictureIntent, 

「Select Picture」),0);

} 

    return true; 

}}

回答

0

從畫廊

選擇圖像
try { 
       Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); 
      } catch (Exception e) { 
       Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show(); 
       Log.e(e.getClass().getName(), e.getMessage(), e); 
      } 

和OnActivityResult

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    switch (requestCode) { 
    case PICK_IMAGE: 

     if (resultCode == Activity.RESULT_OK) { 
      Uri selectedImageUri = data.getData(); 
      try { 
       // OI FILE Manager 
       String filemanagerstring = selectedImageUri.getPath(); 

       // MEDIA GALLERY 
       String selectedImagePath = getPath(selectedImageUri); 

       if (selectedImagePath != null) { 
        filePath = selectedImagePath; 
       } else if (filemanagerstring != null) { 
        filePath = filemanagerstring; 
       } else { 
        Toast.makeText(getApplicationContext(), "Unknown path", 
          Toast.LENGTH_LONG).show(); 

       } 

       if (filePath != null) {   

        decodeFile(filePath); 
       } else { 
        bitmap = null; 
       } 
      } catch (Exception e) { 
       Toast.makeText(getApplicationContext(), "Internal 
        error",Toast.LENGTH_LONG).show(); 

      } 
     } 
     break; 
    default: 
    } 



} 


    //Decode file() where you will get decoded file and then you can use that image 
     //file according to your requirement 

    public void decodeFile(String filePath) { 

    // Decode image size 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
    o.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(filePath, o); 

    // The new size we want to scale to 
    final int REQUIRED_SIZE = 1024; 

    // Find the correct scale value. It should be the power of 2. 
    int width_tmp = o.outWidth, height_tmp = o.outHeight; 
    int scale = 1; 
    while (true) { 
     if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) 
      break; 
     width_tmp /= 2; 
     height_tmp /= 2; 
     scale *= 2; 
    } 

    // Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize = scale; 
    bitmap = BitmapFactory.decodeFile(filePath, o2); 

    image.setImageBitmap(bitmap);// set ImageView in your case set Layout 
       //background 

} 
+0

謝謝!我沒有onActivityResult,所以當我嘗試複製你的代碼時,我得到了一堆錯誤? –

+0

@DeclanMorgan cretae該方法,並不只是複製code..try調試它,並根據您的需求進行更改 –

0

嘗試。 這不是最好的辦法。但它滿足您的需求。

XML文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/rl" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<ImageView 
    android:id="@+id/img" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:scaleType="fitXY" /> 

<Button 
    android:id="@+id/butt" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:text="Click Me" /> 

的Java文件

public class MainActivity extends ActionBarActivity { 

private static int RESULT_LOAD_IMG = 1; 
String path = ""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button btn = (Button) findViewById(R.id.butt); 
    btn.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(
        Intent.ACTION_PICK, 
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
      startActivityForResult(Intent.createChooser(i, "Select Icon"), 
        RESULT_LOAD_IMG); 
     } 
    }); 
} 

public String getPath(Uri uri) { 
    String[] projection = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = managedQuery(uri, projection, null, null, null); 

    int column_index = cursor 
      .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 

@Override 
protected void onActivityResult(int arg0, int arg1, Intent arg2) { 
    super.onActivityResult(arg0, arg1, arg2); 
    try { 

     if (arg0 == RESULT_LOAD_IMG && arg1 == RESULT_OK && null != arg2) { 
      Uri selectedImage = arg2.getData(); 
      path = getPath(selectedImage); 

      ImageView iv = (ImageView) findViewById(R.id.img); 
      iv.setImageURI(selectedImage); 

     } else { 
      Toast.makeText(getApplicationContext(), 
        "You haven't picked Image", Toast.LENGTH_LONG).show(); 
     } 

    } catch (Exception e) { 
     Toast.makeText(getApplicationContext(), "Something went wrong", 
       Toast.LENGTH_LONG).show(); 
    } 
} 
相關問題