본문 바로가기

Android

[안드로이드]Adapter사용하기

정리가 잘 된 글이 있어서 퍼왔다.


안드로이드: 인텐트 (Intent) 와 액티비티 전환 예제 (ListView + Adapter 응용)

 

일전에 인텐트(Intent) 로 액티비티(화면)전환 하는 예제에 대한 포스팅을 했습니다 (아래 링크 참조)

안드로이드 액티비티(화면)전환, 인텐트 #2 (인텐트 값 전달하기) 
안드로이드 액티비티(화면)전환, 인텐트 #1 (기초) 

 

이번에는 리스트뷰(ListView) 를 사용하여 리스트가 나열된 상태에서 원하는 내용을 클릭하면 해당 목록의 상세페이지(액티비티)로 화면전환이 되고, 이때 인텐트(Intent)로 필요한 정보가 함께 전달이 되어 새로 열리는 화면(액티비티)에 보여지게 하겠습니다.

우선 실행결과물을 먼저 보여드립니다.
(최근 온라인 상의 인기가요 Top10 목록입니다.  응답하라1988 관련 곡들이 많네요 ^^) 

 

              아래 목록 (ListView)에서 클릭하면 우측 화면으로 전환

                   

 

 

기본적인 예제 작업 내역을 요약하면

1. 다량의 데이터 준비
    : 이미지 준비
    : 텍스트 준비
    : 해당목록을 담을 클래스 준비 ( class Song )

2. 새로운 액티비티 준비
    : songdetail.xml
    : SongDetail. 액티비티 준비 (인텐트 받아와서 출력)
   : AndroidManifest.xml 에 액티비티 추가

3. MainActivity 에서
    : 리스트 뷰 항목에 들어갈 레이아웃 준비 (row.xml)
    : 리스브튜의 아답타 준비   ( class MyAdapter ), 필요 메소드 구현, 특히 getView() !!
    : 리스트뷰 클릭시 인텐트 (Intent) 생성하고 position 값을 이용하여 인텐트로 넘길값들을 넘긴다

 

[ row.xml ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/abc_btn_radio_to_on_mtrl_015" />
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Title"
        android:textColor="#000"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_alignParentRight="true"
        android:textColor="#000"
        android:text="Artist"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>
cs

[songdetail.xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/abc_btn_radio_to_on_mtrl_015" />
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imageView1"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:text="Artist"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>
cs

 

[activity_main.xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="인기가요 TOP10 - 클릭하세요."
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
 
</LinearLayout>
cs

 

[AndroidManifest.xml] 파일에 다음 액티비티 추가

  <activity android:name=".SongDetail"></activity>
 
[SondDetail.java]  : 클릭했을때 전환되는 액티비티
public class SongDetail extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songdetail);

TextView tvTitle = (TextView)findViewById(R.id.textView1);
TextView tvArtist = (TextView)findViewById(R.id.textView2);
ImageView iv = (ImageView)findViewById(R.id.imageView1);

Intent intent = getIntent(); // 보내온 Intent를 얻는다
tvTitle.setText(intent.getStringExtra("title"));
tvArtist.setText(intent.getStringExtra("artist"));
iv.setImageResource(intent.getIntExtra("img", 0));
} // end of onCreate
} // end of class
 
 

[MainActivity.java]

public class MainActivity extends AppCompatActivity {
ArrayList<Song> al = new ArrayList<Song>(); // Top10 곡명을 담을 리스트

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 인기가요 순위 데이터 (다량의 데이터 준비)
al.add(new Song("소녀",R.drawable.img01,"오혁(Hyukk Oh)"));
al.add(new Song("Prologue",R.drawable.img02,"허각"));
al.add(new Song("못먹는 감 (Sour Grapes)",R.drawable.img03,"산이(San E)"));
al.add(new Song("걱정말아요 그대",R.drawable.img04,"이적"));
al.add(new Song("그날을 내 등 뒤로",R.drawable.img05,"허각"));
al.add(new Song("청춘 (feat. 김창완)",R.drawable.img06,"김필(Kim Feel"));
al.add(new Song("Hot Pink",R.drawable.img07,"EXID(이엑스아이디)"));
al.add(new Song("널 생각해",R.drawable.img08,"윤하(Younha/ユンナ)"));
al.add(new Song("사랑은 가슴이 시킨다 Part.3",R.drawable.img09,"버즈(Buzz)"));
al.add(new Song("또 다시 사랑",R.drawable.img10,"임창정"));


MyAdapter adapter = new MyAdapter(
getApplicationContext(), // 현재화면의 제어권자
R.layout.row, // 리스트뷰의 한행의 레이아웃
al); // 데이터

ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);

lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// 상세정보 화면으로 이동하기(인텐트 날리기)
// 1. 다음화면을 만든다
// 2. AndroidManifest.xml 에 화면을 등록한다
// 3. Intent 객체를 생성하여 날린다
Intent intent = new Intent(
getApplicationContext(), // 현재화면의 제어권자
SongDetail.class); // 다음넘어갈 화면

// intent 객체에 데이터를 실어서 보내기
// 리스트뷰 클릭시 인텐트 (Intent) 생성하고 position 값을 이용하여 인텐트로 넘길값들을 넘긴다
intent.putExtra("title", al.get(position).title);
intent.putExtra("img", al.get(position).img);
intent.putExtra("artist", al.get(position).artist);

startActivity(intent);
}
});
} // end of onCreate
} // end of class

class MyAdapter extends BaseAdapter { // 리스트 뷰의 아답타
Context context;
int layout;
ArrayList<Song> al;
LayoutInflater inf;
public MyAdapter(Context context, int layout, ArrayList<Song> al) {
this.context = context;
this.layout = layout;
this.al = al;
inf = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return al.size();
}
@Override
public Object getItem(int position) {
return al.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null) {
convertView = inf.inflate(layout, null);
}
ImageView iv = (ImageView)convertView.findViewById(R.id.imageView1);
TextView tvName = (TextView)convertView.findViewById(R.id.textView1);
TextView tvInfo = (TextView)convertView.findViewById(R.id.textView2);

Song m = al.get(position);
iv.setImageResource(m.img);
tvName.setText(m.title);
tvInfo.setText(m.artist);

return convertView;
}
}

class Song { // 자바빈
String title = ""; // 곡 title
int img; // 앨범 이미지
String artist = ""; // artist
public Song(String title, int img, String artist) {
super();
this.title = title;
this.img = img;
this.artist = artist;
}
public Song() {}
}
출처 - http://bitsoul.tistory.com/95