2011-07-06 21 views
37

Tôi đang thêm một vài mục mẫu trong ứng dụng của mình để nó trông không trống khi người dùng nhìn vào nó lần đầu tiên. Danh sách với các mục mẫu phải có hình ảnh và hình ảnh tôi sẽ sử dụng đã được lưu trữ trong thư mục/res/drawable của ứng dụng.Lấy URI của một hình ảnh được lưu trữ trong drawable

Vì tôi đã có phương thức tải các ảnh từ một URI, tôi muốn đưa URI vào /res/drawable/myImage.jpg nhưng dường như tôi không thể làm đúng.

Luồng như sau: Tạo mục có chuỗi đại diện cho URI của hình ảnh. Gửi danh sách các mục vào Danh sách Danh sách tải hình ảnh trong tác vụ nền bằng cách chuyển đổi chuỗi thành URL và sau đó chạy url.openStream();

Tôi đã thử một vài tùy chọn cho URI mà không thành công. "android.resource: // ....." nói unknow protocoll "file: //" không tìm thấy file

Vì vậy, ngay bây giờ tôi là một chút mất khoảng cách để sửa lỗi này ..

+1

Câu trả lời của @Pixie hoạt động. –

Trả lời

69

bạn nên sử dụng ContentResolver để mở URI tài nguyên:

Uri uri = Uri.parse("android.resource://your.package.here/drawable/image_name"); 
InputStream stream = getContentResolver().openInputStream(uri); 

Ngoài ra bạn có thể mở tập tin và nội dung URI sử dụng phương pháp này.

+0

Tôi nhận được MalformedUrlException cho các mục sau: Đường dẫn Uri = Uri.parse ("android.resource: //se.javalia.myDrinks/drawable/image0109 "); Hình ảnh được lưu trong thư mục drawable và là tệp jpg. – Roland

+0

Điều đó thật lạ vì' Uri.parse() 'không được ném ngoại lệ này. Khi bạn phân tích cú pháp' Uri' nó chỉ cần kiểm tra cho một tham chiếu 'null' nhưng không thực sự phân tích cú pháp nó – Michael

+0

@Roland Bạn đã làm sai ở đâu đó.Điều này làm việc rất tốt –

25

Đây là những gì bạn thực sự cần:

Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
"://" + getResources().getResourcePackageName(R.drawable.ic_launcher) 
+ '/' + getResources().getResourceTypeName(R.drawable.ic_launcher) + '/' + getResources().getResourceEntryName(R.drawable.ic_launcher)); 
+0

Điều này có cần sự cho phép không? Tôi không thể sử dụng số này – lirui

+1

Tôi không nghĩ vậy. Lỗi là gì? – xnagyg

33
/** 
* get uri to drawable or any other resource type if u wish 
* @param context - context 
* @param drawableId - drawable res id 
* @return - uri 
*/ 
public static final Uri getUriToDrawable(@NonNull Context context, 
             @AnyRes int drawableId) { 
    Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
      "://" + context.getResources().getResourcePackageName(drawableId) 
      + '/' + context.getResources().getResourceTypeName(drawableId) 
      + '/' + context.getResources().getResourceEntryName(drawableId)); 
    return imageUri; 
} 

dựa trên trên - tinh chỉnh phiên bản dành cho bất kỳ tài nguyên:

/** 
* get uri to any resource type 
* @param context - context 
* @param resId - resource id 
* @throws Resources.NotFoundException if the given ID does not exist. 
* @return - Uri to resource by given id 
*/ 
public static final Uri getUriToResource(@NonNull Context context, 
             @AnyRes int resId) 
          throws Resources.NotFoundException { 
    /** Return a Resources instance for your application's package. */ 
    Resources res = context.getResources(); 
    /** 
    * Creates a Uri which parses the given encoded URI string. 
    * @param uriString an RFC 2396-compliant, encoded URI 
    * @throws NullPointerException if uriString is null 
    * @return Uri for this given uri string 
    */ 
    Uri resUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
      "://" + res.getResourcePackageName(resId) 
      + '/' + res.getResourceTypeName(resId) 
      + '/' + res.getResourceEntryName(resId)); 
    /** return uri */ 
    return resUri; 
} 

một số thông tin:

From the Java Language spec.: 

"17.5 Final Field Semantics 

... when the object is seen by another thread, that thread will always 
see the correctly constructed version of that object's final fields. 
It will also see versions of any object or array referenced by 
those final fields that are at least as up-to-date as the final fields 
are." 

In that same vein, all non-transient fields within Uri 
implementations should be final and immutable so as to ensure true 
immutability for clients even when they don't use proper concurrency 
control. 

For reference, from RFC 2396: 

"4.3. Parsing a URI Reference 

    A URI reference is typically parsed according to the four main 
    components and fragment identifier in order to determine what 
    components are present and whether the reference is relative or 
    absolute. The individual components are then parsed for their 
    subparts and, if not opaque, to verify their validity. 

    Although the BNF defines what is allowed in each component, it is 
    ambiguous in terms of differentiating between an authority component 
    and a path component that begins with two slash characters. The 
    greedy algorithm is used for disambiguation: the left-most matching 
    rule soaks up as much of the URI reference string as it is capable of 
    matching. In other words, the authority component wins." 

...

3. URI Syntactic Components 

    The URI syntax is dependent upon the scheme. 
    In general, absolute URI are written as follows: 

    <scheme>:<scheme-specific-part> 

    An absolute URI contains the name of the scheme being used (<scheme>) 
    followed by a colon (":") and then a string (the <scheme-specific-part>) 
    whose interpretation depends on the scheme. 

    The URI syntax does not require that the scheme-specific-part have any 
    general structure or set of semantics which is common among all URI. 
    However, a subset of URI do share a common syntax for representing 
    hierarchical relationships within the namespace. This "generic URI" 
    syntax consists of a sequence of four main components: 

    <scheme>://<authority><path>?<query> 

nguồn:

TRANH CHẤP

câu trả lời này là đúng, tuy nhiên phần về lĩnh vực thức không phải là - nó không có gì liên quan đến việc trả lời r - Boris Treukhov

@BorisTreukhov - xin hãy giải thích cho chúng tôi những gì u có nghĩa là bởi "phần về lĩnh vực thức là không đúng" - câu hỏi - làm thế nào để có được uri để ...? xây dựng cách nó có thể được phân tích cú pháp (cách phân tích cú pháp uri? xem câu trả lời)

package android.net; 

/** 
* Immutable URI reference. A URI reference includes a URI and a fragment, the 
* component of the URI following a '#'. Builds and parses URI references 
* which conform to 
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>. 
* 
* <p>In the interest of performance, this class performs little to no 
* validation. Behavior is undefined for invalid input. This class is very 
* forgiving--in the face of invalid input, it will return garbage 
* rather than throw an exception unless otherwise specified. 
*/ 
public abstract class Uri implements Parcelable, Comparable<Uri> { ... } 
+0

tuyệt vời nó hoạt động. cảm ơn bạn –

+0

Câu trả lời này là chính xác, tuy nhiên phần về các trường cuối cùng không phải là - nó không liên quan gì đến câu trả lời –

+0

@BorisTreukhov - vui lòng nhận xét về chỉnh sửa – ceph3us

Các vấn đề liên quan