Xamarin.Android 갤러리 컨트롤

Gallery 는 가로 스크롤 목록에서 항목을 표시하는 데 사용되는 레이아웃 위젯으로, 현재 선택 영역을 보기의 가운데에 배치합니다.

Important

이 위젯은 Android 4.1(API 수준 16)에서 더 이상 사용되지 않습니다.

이 자습서에서는 사진 갤러리를 만든 다음 갤러리 항목을 선택할 때마다 알림 메시지를 표시합니다.

콘텐츠 보기 GalleryMain.axml 대해 레이아웃을 설정한 후에는 레이아웃에서 .를 사용하여 FindViewById캡처됩니다. 입니다.Adapter 속성은 사용자 지정 어댑터( ImageAdapter)를 dallery에 표시할 모든 항목의 원본으로 설정하는 데 사용됩니다. 다음 ImageAdapter 단계에서 만들어집니다.

갤러리의 항목을 클릭할 때 작업을 수행하려면 익명 대리자가 다음을 구독합니다. ItemClick 이벤트 를 표시합니다. Toast 이러한 항목의 인덱스 위치(0부터 시작)를 표시하는 입니다(실제 시나리오에서 위치는 다른 작업에 대한 전체 크기 이미지를 가져오는 데 사용될 수 있음).

먼저 그리기 가능한 리소스 디렉터리(리소스/그리기 가능)에 저장된 이미지를 참조하는 ID 배열을 포함하여 몇 가지 멤버 변수가 있습니다.

다음은 클래스 생성자입니다. 여기서 Context 인스턴스가 ImageAdapter 정의되고 로컬 필드에 저장됩니다. 다음으로 , 에서 BaseAdapter상속된 몇 가지 필수 메서드를 구현합니다. 생성자 및 Count 속성은 설명이 다릅니다. 일반적 으로 GetItem(int) 는 어댑터의 지정된 위치에 있는 실제 개체를 반환해야 하지만 이 예제에서는 무시됩니다. 마찬가지로 GetItemId(int) 는 항목의 행 ID를 반환해야 하지만 여기서는 필요하지 않습니다.

메서드는 이미지를 적용하는 작업을 수행합니다. ImageView 에 포함되는 Gallery 이 메서드에서 멤버 Context 는 새 ImageView를 만드는 데 사용됩니다. 입니다.ImageView 는 그리기 가능한 리소스의 로컬 배열에서 이미지를 적용하여 준비됩니다. Gallery.LayoutParams 이미지의 높이 및 너비를 지정하고 배율을 ImageView 을 선택한 다음 마지막으로 생성자에서 가져온 스타일 지정 가능한 특성을 사용하도록 배경을 설정합니다.

다른 이미지 크기 조정 옵션은 참조 ImageView.ScaleType 하세요.

연습

HelloGallery라는 새 프로젝트를 시작합니다.

Screenshot of new Android project in the New Solution dialog

사용하려는 일부 사진을 찾거나 이러한 샘플 이미지를 다운로드합니다. 프로젝트의 Resources/Drawable 디렉터리에 이미지 파일을 추가합니다. 속성 창에서 각각에 대한 빌드 작업을 AndroidResource설정합니다.

Resources/Layout/Main.axml을 열고 다음을 삽입합니다.

<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

다음 코드를 열고 MainActivity.cs 삽입합니다. OnCreate() 메서드:

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    // Set our view from the "main" layout resource
    SetContentView (Resource.Layout.Main);

    Gallery gallery = (Gallery) FindViewById<Gallery>(Resource.Id.gallery);

    gallery.Adapter = new ImageAdapter (this);

    gallery.ItemClick += delegate (object sender, Android.Widget.AdapterView.ItemClickEventArgs args) {
        Toast.MakeText (this, args.Position.ToString (), ToastLength.Short).Show ();
    };
}

해당 서브클래스라는 ImageAdapter 새 클래스를 만듭니다.BaseAdapter

public class ImageAdapter : BaseAdapter
{
    Context context;

    public ImageAdapter (Context c)
    {
          context = c;
    }

    public override int Count { get { return thumbIds.Length; } }

    public override Java.Lang.Object GetItem (int position)
    {
          return null;
    }

    public override long GetItemId (int position)
    {
          return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public override View GetView (int position, View convertView, ViewGroup parent)
    {
          ImageView i = new ImageView (context);

          i.SetImageResource (thumbIds[position]);
          i.LayoutParameters = new Gallery.LayoutParams (150, 100);
          i.SetScaleType (ImageView.ScaleType.FitXy);

          return i;
    }

    // references to our images
    int[] thumbIds = {
            Resource.Drawable.sample_1,
            Resource.Drawable.sample_2,
            Resource.Drawable.sample_3,
            Resource.Drawable.sample_4,
            Resource.Drawable.sample_5,
            Resource.Drawable.sample_6,
            Resource.Drawable.sample_7
     };
}

애플리케이션을 실행합니다. 아래 스크린샷과 같습니다.

Screenshot of HelloGallery displaying sample images

참조

이 페이지의 일부는 Android 오픈 소스 프로젝트에서 만들고 공유하고 Creative Commons 2.5 특성 라이선스에 설명된 용어에 따라 사용되는 작업을 기반으로 하는 수정 사항입니다.