2017-03-31 64 views
0

在我的android應用程序中,我從http請求中提取數據。如何動態加載滑動圖片(Android)?

在我的佈局中,我想用Glide庫動態顯示圖像。

我得到的圖像網址,但我無法找到一種方式來顯示他們在我的佈局。

在我的佈局文件,我有:

<LinearLayout 
    android:id="@+id/social_media_layout" 
    android:layout_width="match_parent" 
    android:orientation="horizontal" 
    android:layout_height="60dp" 
    android:gravity="center_vertical"> 

    </LinearLayout> 

不知怎的,我想在我的LinearLayout添加imageviews(動態)。

例如:如果我從請求中獲得2個圖像url,我需要在我的linearlayout中使用兩個imageviews。

注意:我想用Glide庫加載圖像。

任何想法都是有益的。

謝謝。

+0

獲取LinearLayout視圖實例,然後創建您的ImageView並添加所需的圖像,然後使用linearLayout.addView(image);添加視圖 –

+1

很可能,您應該使用ListView或RecyclerView而不是LinearLayout。 –

回答

1

你可以做一個新的XML文件item_social_media.xml

例如

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="60dp" > 

    <ImageView 
     android:id="@+id/social_media_icon" 
     /> 

     <!-- More customization as needed --> 

</RelativeLayout> 

你可以說膨脹,並添加到LinearLayout中。

final Context context = MainActivity.this; // TODO: Get a context 

// Inflate and update the view 
View socialMediaItem = LayoutInflater.from(context).inflate(R.layout.item_social_media); 
ImageView icon = (ImageView) socialMediaItem.findViewById(R.id.social_media_icon); 
// TODO: Glide ... into(icon); 

// Add to the LinearLayout 
linearLayout.addView(socialMediaItem); 
1

您應該更好地使用ListView或RecycleView。但是,如果你堅持將它們添加到LinearLayout中動態,則:

LinearLayout layout = (LinearLayout)findViewById(R.id.social_media_layout); 

// assuming that image_urls_list contains the images urls 
for(int i=0;i<image_urls_list.size();i++) 
{ 
    ImageView image = new ImageView(this); 

    // set whatever width and height you want to give 
    image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100,100)); 

    // load image using Glide 
    Glide.with(context).load(image_urls_list.get(i)).into(image); 

    // Adds the view to the layout 
    layout.addView(image); 
} 

你可能要一個Horizo​​ntalScrollView標籤作爲父標記添加到您的LinearLayout,讓您可以水平滾動。