将 facebook 的个人资料图片设置为 LinearLayout 背景

Setting facebook's profile picture as a LinearLayout background

我一直在尝试将我的 Facebook 个人资料图片设置为我的应用程序中的 Linearlayout 背景,但没有成功。 这是我尝试执行此操作的两种方法:

第一种方式:从个人资料图片中获取uri并将其转换为drawable

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    LinearLayout banner = (LinearLayout)findViewById(R.id.banner);
       Profile profile = Profile.getCurrentProfile();
        if(profile != null){
           // profile_pic_id.setProfileId((profile.getId()));
            Drawable d;
            Uri uri = profile.getLinkUri();
            //also tried profile.getProfilePictureUri(random_num,random_num)
            try {

                InputStream inputStream = getContentResolver().openInputStream(uri);
                 d = Drawable.createFromStream(inputStream, uri.toString());
            } catch (FileNotFoundException e) {
                d = getResources().getDrawable(R.drawable.blue_material);
            }
            banner.setBackgroundDrawable(d);
        }
}

现在这总是抛出异常所以我得到的 Drawable 是 blue_material 一个(在 catch 块中设置的 Drawable ),所以如果有人知道它为什么抛出一个一直例外,我将不胜感激。

第二种方式:ProfilePictureView转换为ImageView,然后在ImageView上使用getDrawable()

 ProfilePictureView profilePictureFB=(ProfilePictureView)findViewById(R.id.pic);
 profilePictureFB.setProfileId((profile.getId()));
 ImageView fbImage = ( ( ImageView)profilePictureFB.getChildAt( 0));
 banner.setBackgroundDrawable(fbImage.getDrawable());

现在,当某人没有个人资料照片时,这会导致背景带有 Facebook 放置的默认图片。

AND 每当我使用 decodeStream 时都会抛出异常。(下面的示例)

URL img_url =new URL("https://graph.facebook.com/"+profile.getId()+"/picture?type=normal");
                Bitmap bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap

我不想求助于在 Whosebug 上问这个问题,因为我想自己解决它,但我尝试了很长时间,所以我不得不寻求帮助。

感谢所有回答的人:)

我不确定,但这就是我以前做的

 img_url =new URL("https://graph.facebook.com/"+uname+"/picture?type=normal");
     bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap
     linearlayout.setImageBitmap(bmp);//your linear layout

我解决了!!

我使用了 imageLoader,出于某种原因 url 可以使用它,这里是代码:

        imageView = (ImageView) findViewById(R.id.pic);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageLoader = ImageLoader.getInstance();

        Profile profile = Profile.getCurrentProfile();
        if(profile != null){           
            DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
            imageLoader.displayImage("http://graph.facebook.com/" + profile.getId() + "/picture?width=400&height=400", imageView, options);
           // banner.setBackgroundDrawable(imageView.getDrawable());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);

方法 setScaleType 将我的图像视图扩展到我的所有 LinearLayout。 有关通用图像加载器的更多信息,请访问此 link: https://github.com/nostra13/Android-Universal-Image-Loader