[Xamarin] Android 製作滑動含手勢輪播廣告 +網路圖片 +點擊事件
2016-07-20
之前分享一篇文章關於 Android 製作滑動含手勢輪播廣告 但是那時候用的圖片是由內建的資源,因為剛好朋友在問我這問題,我就順手改寫了一段讓他支援網路圖片,並且點擊之後會有觸發Toast 事件
1.先下載 Source Code ( https://github.com/donma/Xamarin.TestSliderAutoPlay )
2.改寫 MainActivity.cs 將 List<int> ImagesList 改成 List<string> ImagesList ,之後放入的Resource 就變成放入網址
//加入圖片ImagesList = new List<string>();
ImagesList.Add("https://scontent-tpe1-1.xx.fbcdn.net/t31.0-8/1658640_607698415972232_623702357_o.jpg");ImagesList.Add("https://scontent-tpe1-1.xx.fbcdn.net/t31.0-8/1912488_607698419305565_1668011281_o.jpg");ImagesList.Add("https://scontent-tpe1-1.xx.fbcdn.net/v/t1.0-0/p206x206/13615237_1098938063514929_7364534394901397035_n.jpg?oh=20cc9dcc28a6fcda6ffd1ea872c67abe&oe=57EE0EBD");ImagesList.Add("https://scontent-tpe1-1.xx.fbcdn.net/t31.0-8/13662165_1098938066848262_3644920350712659186_o.jpg");ImagesList.Add("https://scontent-tpe1-1.xx.fbcdn.net/t31.0-8/13680021_1098938060181596_8709151440474234547_o.jpg");_adapter = new FragStateSupport(SupportFragmentManager, ImagesList);//這時候把自己Activity 傳入,方便從Fragment 那邊直接呼叫_adapter._Activity = this;其中,我多新增一個_Activity 讓主Activity這邊可以傳遞到Adapter 中,在讓Adapter 傳遞至Fragment 這樣就可以抓到父親的Activity
3.改寫 TestFragment.cs 的 GetBitmapOptionsOfImage 部分,讓他取得Options 之前如果沒有圖片就下載
public BitmapFactory.Options GetBitmapOptionsOfImage(){ //Get only the bounds of the bitmap image BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true, InPurgeable = true,};
//改寫這一段,如果沒有圖片就進行下載if (myBitmap == null)
{ var client = new WebClient();myBitmap = client.DownloadData(itemData);
}
// The result will be null because InJustDecodeBounds == true.Bitmap result = BitmapFactory.DecodeByteArray(myBitmap,0,myBitmap.Length, options);
int imageHeight = options.OutHeight; int imageWidth = options.OutWidth;Console.WriteLine(string.Format("Original Size= {0}x{1}", imageWidth, imageHeight));
return options;}
改寫 OnCreateView 中圖片點擊事件加入Click
using (Bitmap bitmapToDisplay = LoadScaledDownBitmapForDisplay(options, 500, 300)){ivImageView.SetImageBitmap(bitmapToDisplay);
//加入圖片點擊的事件 ivImageView.Click += delegate {Toast.MakeText(_Activity, itemData, ToastLength.Short).Show();
};
}
結果,這都是來自臉書上面的圖片
Source:
https://www.dropbox.com/s/az5yximpic8ljli/SlideTest.WebImage.7z?dl=0
