관리 메뉴

웹개발자의 기지개

ListView 리스트뷰 연습3 - 커스텀 리스트뷰 (Custom ListView) 본문

안드로이드

ListView 리스트뷰 연습3 - 커스텀 리스트뷰 (Custom ListView)

http://portfolio.wonpaper.net 2019. 12. 27. 17:36

ListView 리스트뷰 연습1 - 아이템 단일선택, 다중선택가능
https://wonpaper.tistory.com/159?category=811923


ListView 리스트뷰 연습2 - 동적으로 아이템 추가 삭제
https://wonpaper.tistory.com/160?category=811923

 

이번에는 ListView 를 내가 원하는 xml 화면형식으로 ListView 에 올려 보도록 하자.

 

최종 결과화면
listview_item.xml 을 추가한다.

 

[ listview_item.xml ] - 한줄의 item 화면 구성하는 레이아웃 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
32
33
34
35
36
37
38
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
 
    <LinearLayout
        android:orientation="vertical"
        android:layout_weight="4"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
 
        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:textSize="24dp"
            android:textColor="#000000"
            android:gravity="center_vertical"
            android:layout_weight="2"
            />
        <TextView
            android:id="@+id/textView2"
            android:text="New Text2"
            android:textSize="16dp"
            android:textColor="#666666"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
 
    </LinearLayout>
</LinearLayout>
cs

 

[ activity_main.xml ] 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
 
</LinearLayout>
cs

 

[ ListViewItem.java ] - item 객체모델

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
import android.graphics.drawable.Drawable;
 
public class ListViewItem {
    private Drawable iconDrawable;
    private String title;
    private String desc;
 
    public void setIcon(Drawable icon) {
        iconDrawable = icon;
    }
 
    public Drawable getIcon() {
        return this.iconDrawable;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getTitle() {
        return this.title;
    }
 
    public void setDesc(String desc) {
        this.desc = desc;
    }
 
    public String getDesc() {
        return this.desc;
    }
}
cs

 

그리고, 임의의 아이콘을 아이템별로 추가하려고 한다. Vector Image 형태로 간단히 만들어 보았다.

 

 

[ ListViewAdapter.java ] - 어댑터 생성

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
 
public class ListViewAdapter extends BaseAdapter {
    private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
 
    public ListViewAdapter() {  }
 
    // listviewitem 항목개수
    @Override
    public int getCount() {
        return listViewItemList.size();
    }
 
    // position 위치의 item 값을 리턴
    @Override
    public Object getItem(int position) {
        return listViewItemList.get(position);
    }
 
    // position 위치의 item 의 row id값 리턴
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    // position 위치의 item항목을 View 형식으로 얻어온다.
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();
 
        // listview_item의 layout을 inflate하여 xml을 view로 만들고 convertView 참조 획득
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.listview_item,parent,false);
        }
 
        // 화면에 표시될 View(Layout이 inflate된)으로부터 위젯에 대한 참조 획득
        ImageView iconImageView = (ImageView) convertView.findViewById(R.id.imageView1);
        TextView titleTextView = (TextView) convertView.findViewById(R.id.textView1);
        TextView descTextView = (TextView) convertView.findViewById(R.id.textView2);
 
        // Data Set (listViewItemList) 에서 position에 위치한 데이터참조 획득
        ListViewItem listViewItem = listViewItemList.get(position);
 
        // 아이템 내 각 위젯에 데이터 반영
        iconImageView.setImageDrawable(listViewItem.getIcon());
        titleTextView.setText(listViewItem.getTitle());
        descTextView.setText(listViewItem.getDesc());
 
        return convertView;
    }
 
    // item 데이터 추가
    public void addItem(Drawable icon, String title, String desc) {
        ListViewItem item = new ListViewItem();
        item.setIcon(icon);
        item.setTitle(title);
        item.setDesc(desc);
        listViewItemList.add(item);
    }
 
    // item 삭제
    public void delItem(int position) {
        listViewItemList.remove(position);
    }
}
cs

 

 

[ MainActivity.java ] 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("Custom ListView 예제");
 
        ListView listView = findViewById(R.id.listView1);
 
        ListViewAdapter adapter = new ListViewAdapter();
        listView.setAdapter(adapter);
 
        // 아이템 추가
        adapter.addItem(ContextCompat.getDrawable(this,R.drawable.ic_android_black_24dp),"아이콘1번""24dp Black");
        adapter.addItem(ContextCompat.getDrawable(this,R.drawable.ic_camera_alt_black_24dp),"아이콘2번""24dp Black");
        adapter.addItem(ContextCompat.getDrawable(this,R.drawable.ic_card_membership_black_24dp),"아이콘3번""24dp Black");
 
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 
                ListViewItem item = (ListViewItem) parent.getItemAtPosition(position);
 
                String title = item.getTitle();
                String desc = item.getDesc();
                Drawable icon = item.getIcon();
 
                String str = "id : " + Long.toString(id) + "\r\ntitle : " + title + "\r\ndesc : " + desc;
 
                Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
cs

 

참고 사이트 : https://recipes4dev.tistory.com/43

 

 

Comments