출처 : http://creamnuts.com/wp/?p=436&cpage=1#comment-3404
안드로이드 리스트 뷰를 다음과 같이 구성하여 선택시 선택유지를 하고싶을 경우가 있는데, 이는 커스텀 리스트 뷰 클래스를 작성함으로써 원하는 행동으로 행하게끔 만들 수 있다. 선택해 놓고 선택한것만 데이터를 뽑아내서 조작한다거나 하는 행위들이 가능하게끔 코딩을 해주면 된다.
위 그림과 같이 선택한 아이템을 선택유지하게끔 하고싶어서 이 블로그를 찾았다면 매우 잘 찾아왔다고 할 수 있다. 쓸대없는 말 대신 코드로 설명하겠다.
1. Xml 파일 생성
일단 맨 상단의 “회사명”, “현재가격” 등은 컨텐츠 영역에서 레이아웃을 따로 잡아준거고.. BBK 치킨 등의 아이템이 들어있는 것이 바로 리스트뷰가 변형되어 뿌려진 형태라 할 수 있다. 이것을 구성하기 위해서는 레이아웃을 Xml로 작업을 해주어야 한다.
다음과 같이 Android Xml을 레이아웃 폴더에 생성해 준다.
이름은 간단하게 customlistview.xml 로 정하였다. 그리고 한개의 아이템이 어떠한 식으로 표현될지에 대한 레이아웃 코드를 작성한다.
1 |
<? xml version = "1.0" encoding = "utf-8" ?> |
2 |
< LinearLayout |
3 |
xmlns:android = "http://schemas.android.com/apk/res/android" |
4 |
android:layout_width = "fill_parent" |
5 |
android:layout_height = "fill_parent" |
6 |
android:baselineAligned = "false" |
7 |
android:orientation = "horizontal" |
8 |
> |
9 |
< TextView |
10 |
android:id = "@+id/item1" |
11 |
android:layout_width = "100dip" |
12 |
android:layout_height = "32dip" |
13 |
android:textColor = "#000000" |
14 |
android:background = "#882F32" |
15 |
android:gravity = "center" |
16 |
android:textSize = "10sp" |
17 |
> |
18 |
</ TextView > |
19 |
20 |
< TextView |
21 |
android:id = "@+id/item2" |
22 |
android:layout_width = "85dip" |
23 |
android:layout_height = "32dip" |
24 |
android:textColor = "#000000" |
25 |
android:gravity = "center" |
26 |
android:textSize = "10sp" |
27 |
android:text = "3000" > |
28 |
</ TextView > |
29 |
30 |
< TextView |
31 |
android:id = "@+id/item3" |
32 |
android:layout_width = "85dip" |
33 |
android:layout_height = "32dip" |
34 |
android:textColor = "#000000" |
35 |
android:gravity = "center" |
36 |
android:textSize = "10sp" |
37 |
android:text = "▲ 700" > |
38 |
39 |
</ TextView > |
40 |
41 |
< TextView |
42 |
android:id = "@+id/item4" |
43 |
android:layout_width = "55dip" |
44 |
android:layout_height = "32dip" |
45 |
android:textColor = "#000000" |
46 |
android:gravity = "center" |
47 |
android:textSize = "10sp" |
48 |
android:text = "1" > |
49 |
</ TextView > |
50 |
</ LinearLayout > |
2. 어댑터 작성하기
리스트뷰의 아이템들을 필요한 만큼 넣어서 사용하려면 Adapter 라는 클래스를 사용하여 리스트뷰에 셋팅하여야 한다. 기본형태는 기본 데이터만 받아서 하나의 데이터만을 아이템에 표시해주기 때문에 이를 상속받아 확장할 필요가 있다.
일단 아이템의 데이터를 관리해야 하기 때문에 나중의 편의성이나 확장성을 위하여 DATA 클래스는 따로 만들어서 관리하고, 어뎁터 클래스는 재사용성을 염두해 두고 작성할 필요가 있지만, 언제까지나 예시이므로.. 간단하게 만들어보도록 하겠다.
DATA.java
1 |
public class DATA{ |
2 |
private String m_name; // 주식명 |
3 |
private int m_price; // 주식 가격 |
4 |
private int m_contrast; // 대비 |
5 |
private int m_stockholding; // 보유 주식 |
6 |
7 |
public DATA(String name, int price){ |
8 |
m_name = name; // 이름 |
9 |
m_price = price; // 초기가격 |
10 |
} |
11 |
12 |
public String getName(){ |
13 |
return m_name; |
14 |
} |
15 |
16 |
public int getPrice(){ |
17 |
return m_price; |
18 |
} |
19 |
20 |
public int getContrast(){ |
21 |
return m_contrast; |
22 |
} |
23 |
24 |
public int getStockHolding(){ |
25 |
return m_stockholding; |
26 |
} |
27 |
28 |
public void setPrice( int price){ |
29 |
m_price = price; |
30 |
} |
31 |
32 |
public void setContrast( int contrast){ |
33 |
m_contrast = contrast; |
34 |
} |
35 |
36 |
public void setStockholding( int stock){ |
37 |
m_stockholding = stock; |
38 |
} |
39 |
} |
다음은 어뎁터를 작성해야 하는데, 필수 메서드 빼고는 필요 용도에 따라 상속받아서 확장하는 형태로 만들어두면 편하게 사용이 가능할 것이라 생각된다.
어차피 남보라고 포스팅 하는 것 보다 나 편하라고 포스팅 하는 것이 더 강하므로.. 자세한 설명은 생략한다. 다만.. 댓글로 물어보거나 하면, 친절하게 알려줄 용의는 있다. 사실 별것 아닌 코드니 대충 보면 감이 오리라 생각한다.
1 |
public class MyAdapter extends ArrayAdapter<DATA>{ |
2 |
// *********************************************************** |
3 |
// @ 내부 상수 |
4 |
// *********************************************************** |
5 |
static final String TAG = "JusicAdapter" ; |
6 |
7 |
// *********************************************************** |
8 |
// @ 내부 필드 |
9 |
// *********************************************************** |
10 |
private ArrayList<DATA> m_items; |
11 |
private int m_nSelectedPos = - 1 ; |
12 |
private int m_layout; |
13 |
LayoutInflater m_layoutInflater; |
14 |
15 |
// *********************************************************** |
16 |
// @ 생성자 |
17 |
// *********************************************************** |
18 |
public MyAdapter(Context context, int layout, ArrayList<DATA> items) { |
19 |
super (context, layout, items); |
20 |
m_items = items; |
21 |
m_layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); |
22 |
m_layout = layout; |
23 |
} |
24 |
25 |
// *********************************************************** |
26 |
// @ 메소드 |
27 |
// *********************************************************** |
28 |
public void setSelectedPosition( int pos){ |
29 |
// 같이 것이 눌렸다면.. |
30 |
if (m_nSelectedPos == pos){ |
31 |
m_nSelectedPos = - 1 ; |
32 |
notifyDataSetChanged(); |
33 |
return ; |
34 |
} |
35 |
else { |
36 |
m_nSelectedPos = pos; |
37 |
// inform the view of this change |
38 |
notifyDataSetChanged(); |
39 |
} |
40 |
} |
41 |
42 |
public void setImtes(ArrayList<DATA> items){ |
43 |
m_items = items; |
44 |
} |
45 |
46 |
public int getSelectedPosition(){ |
47 |
return m_nSelectedPos; |
48 |
} |
49 |
50 |
@Override |
51 |
public int getCount() { |
52 |
return m_items.size(); |
53 |
} |
54 |
55 |
@Override |
56 |
public DATA getItem( int position) { |
57 |
return m_items.get(position); |
58 |
} |
59 |
60 |
@Override |
61 |
public long getItemId( int position) { |
62 |
return position; |
63 |
} |
64 |
65 |
@Override |
66 |
public View getView( int position, View convertView, ViewGroup parent) { |
67 |
DATA item = getItem(position); |
68 |
69 |
if (convertView == null ){ |
70 |
convertView = m_layoutInflater.inflate(m_layout, parent, false ); |
71 |
} |
72 |
73 |
TextView name = (TextView)convertView.findViewById(R.id.item1); |
74 |
TextView price = (TextView)convertView.findViewById(R.id.item2); |
75 |
TextView contrast = (TextView)convertView.findViewById(R.id.item3); |
76 |
TextView stockholding = (TextView)convertView.findViewById(R.id.item4); |
77 |
78 |
name.setBackgroundColor( 0xff882F32 ); |
79 |
name.setText(item.getName()); |
80 |
name.setGravity(Gravity.CENTER); |
81 |
price.setText(Integer.toString(item.getPrice())); |
82 |
83 |
int nContrast = item.getContrast(); |
84 |
85 |
// 대비 설정 |
86 |
if (nContrast == 0 ){ |
87 |
contrast.setText( "-" ); |
88 |
} |
89 |
else { |
90 |
// 음수 |
91 |
if (nContrast < 0 ){ |
92 |
// 가격설정 |
93 |
contrast.setText( "▼" + Integer.toString(item.getContrast())); |
94 |
} |
95 |
// 양수 |
96 |
else { |
97 |
contrast.setText( "▲" + Integer.toString(item.getContrast())); |
98 |
} |
99 |
} |
100 |
// 보유 주 |
101 |
stockholding.setText(Integer.toString(item.getStockHolding())); |
102 |
103 |
// change the row color based on selected state |
104 |
// 색상을 변경하여 뿌려준다. |
105 |
if (m_nSelectedPos == position){ |
106 |
convertView.setBackgroundColor( 0xFFffda00 ); |
107 |
name.setBackgroundColor( 0xFFdd6f00 ); |
108 |
} |
109 |
else { |
110 |
convertView.setBackgroundColor(Color.WHITE); |
111 |
name.setBackgroundColor( 0xff882F32 ); |
112 |
} |
113 |
114 |
return convertView; |
115 |
} |
116 |
} |
3. 연동하기
자 여기 까지 되었다면 이제 리스트뷰에 연동해서 뿌리는 일만 남았다. 해당 리스트뷰를 보여줄 곳의 Xml에 리스트뷰를 추가하고 해당 엑티비티에서 받아서 설정만 해주면 되는 것이다.
1 |
< LinearLayout |
2 |
android:layout_width = "fill_parent" |
3 |
android:layout_height = "wrap_content" |
4 |
android:orientation = "horizontal" |
5 |
> |
6 |
< TextView |
7 |
android:layout_width = "100dip" |
8 |
android:layout_height = "wrap_content" |
9 |
android:gravity = "center" |
10 |
android:text = "회사명" > |
11 |
</ TextView > |
12 |
13 |
< TextView |
14 |
android:layout_width = "85dip" |
15 |
android:layout_height = "wrap_content" |
16 |
android:gravity = "center" |
17 |
android:text = "현재가격" > |
18 |
</ TextView > |
19 |
20 |
< TextView |
21 |
android:layout_width = "85dip" |
22 |
android:layout_height = "wrap_content" |
23 |
android:gravity = "center" |
24 |
android:text = "대비" > |
25 |
</ TextView > |
26 |
27 |
< TextView |
28 |
android:layout_width = "55dip" |
29 |
android:layout_height = "wrap_content" |
30 |
android:gravity = "center" |
31 |
android:text = "보유주" > |
32 |
</ TextView > |
33 |
34 |
</ LinearLayout > |
35 |
36 |
< ListView |
37 |
android:id = "@+id/list" |
38 |
android:layout_width = "fill_parent" |
39 |
android:layout_height = "fill_parent" |
40 |
android:layout_weight = "1" > |
41 |
</ ListView > |
1 |
public class GameActivity extends Activity{ |
2 |
3 |
// *********************************************************** |
4 |
// @ 내부 필드 |
5 |
// *********************************************************** |
6 |
private ListView m_listView; |
7 |
private ArrayList<DATA> m_orders; |
8 |
9 |
// *********************************************************** |
10 |
// @ 메소드 |
11 |
// *********************************************************** |
12 |
@Override |
13 |
protected void onCreate(Bundle savedInstanceState) { |
14 |
super .onCreate(savedInstanceState); |
15 |
setContentView(R.layout.gameview); |
16 |
17 |
DATA data1 = new DATA( "주식1" , 1000 ); |
18 |
DATA data2 = new DATA( "주식2" , 2000 ); |
19 |
20 |
m_orders = new ArrayList<DATA>(); |
21 |
22 |
m_orders.add(data1); |
23 |
m_orders.add(data2); |
24 |
25 |
m_adpter = new MyAdapter( this , R.layout.customlistview, m_orders); |
26 |
m_listView.setAdapter(m_adpter); |
27 |
28 |
m_listView.setOnItemClickListener( new OnItemClickListener() { |
29 |
@Override |
30 |
public void onItemClick(AdapterView<?> arg0, View view, |
31 |
int position, long id) { |
32 |
// user clicked a list item, make it "selected" |
33 |
m_adpter.setSelectedPosition(position); |
34 |
} |
35 |
}); |
36 |
} |
이런식으로 구성하면 되겠다. 매우 쉽고 간단하다.. 응용하면 무궁무진한 형태의 리스트뷰가 나올 수 있다.
'Program > Android Java' 카테고리의 다른 글
안드로이드 동영상 스트리밍 재생 (0) | 2011.10.23 |
---|---|
Toast - View를 사용하여 출력하기 (xml) (0) | 2011.10.06 |
Intro화면 코드 (0) | 2011.09.21 |
[Android 2.3] DownloadManager 사용하기 (0) | 2011.09.21 |
안드로이드에서 아이폰처럼 휠위젯 사용하기 (0) | 2011.09.21 |