티스토리 뷰

Android/정리

리스트 뷰 (ListView)

란텔 2016. 9. 7. 13:53

리스트뷰는 말 그대로 view를 리스트의 형태로 보여주는 것을 얘기한다.


리스트뷰는 여러 리스트 목록 중에 하나의 목록을 선택 가능하다. 그래서 '선택 위젯'이라고 한다.


'선택 위젯'에는 리스트, 스피너, 그리드, 갤러리 등이 있다.



리스트뷰를 만들기 위해서는 다음과 같은 절차를 따라야 한다.

1. 리스트 뷰의 목록이 될 하나의 디자인 레이아웃 xml을 만든다. 그리고 이것을 액티비티에 인플레이션 하는 자바 코드를 작성한다.

2. 하나의 리스트뷰 목록에 들어갈 정보를 클래스로 정의한다.

3. 리스트뷰에 필요한 뷰를 가져오는 어댑터를 확장한 클래스를 만든다.

4. 메인 액티비티에서 <ListView>정보를 가져와서 setAdapter메서드를 이용해 3번의 어댑터 확장 클래스를 설정한다.





list_view.xml

리스트뷰 하나하나의 목록이 될 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
 
    <ImageView
        android:id="@+id/imageItem"
        android:layout_width="100dp"
        android:layout_height="65dp"
        android:padding="0dp"
        />
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        
        <TextView
            android:id="@+id/contentItem1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
 
        <TextView
            android:id="@+id/contentItem2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
 
    </LinearLayout>
 
</LinearLayout>
 
cs




ListViewObject.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
public class ListViewObject extends LinearLayout {
 
    ImageView imageItem;
    TextView contentItem1, contentItem2;
 
    public ListViewObject(Context c, MakeItemInfo mii){
        super(c);
 
        LayoutInflater inflater = LayoutInflater.from(c);
        //list_view 레이아웃의 내용을 LinearLayout 요소에 넣는다.
        inflater.inflate(R.layout.list_view, thistrue);
 
        settingFindId();
    }
 
    void settingFindId(){
        imageItem =  (ImageView) findViewById(R.id.imageItem);
        contentItem1 = (TextView) findViewById(R.id.contentItem1);
        contentItem2 = (TextView) findViewById(R.id.contentItem2);
    }
 
    public void setImage(Drawable drawable){
        imageItem.setImageDrawable(drawable);
    }
 
    public void setText1(String text1){
        contentItem1.setText(text1);
    }
 
    public void setText2(String text2){
        contentItem2.setText(text2);
    }
 
}
cs



MakeItemInfo.java

list_view.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
public class MakeItemInfo {
   private Drawable drawable;
    private String text1;
    private String text2;
 
 
    public MakeItemInfo(Drawable drawable, String text1, String text2){
        this.drawable = drawable;
        this.text1 = text1;
        this.text2 = text2;
    }
 
    public Drawable getDrawable() {
        return drawable;
    }
 
    public String getText1() {
        return text1;
    }
 
    public String getText2() {
        return text2;
    }
 
 
    @Override
    public String toString() {
        return "[ " + this.drawable.toString() + ", " + this.text1 + ", " + this.text2 + " ]";
    }
}
cs




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
public class ListViewAdapter extends BaseAdapter {
    private Context context;
    List<MakeItemInfo> list = new ArrayList<>();
 
    public ListViewAdapter(Context context){
        this.context = context;
    }
 
    //리스트뷰의 목록이 되는 데이터 갯수를 반환. 정확한 갯수를 반환하지 않으면 심각한 예외를 발생할 수 있다.
    @Override
    public int getCount() {
        return list.size();
    }
 
    @Override
    public long getItemId(int id) {
        return id;
    }
 
    @Override
    public MakeItemInfo getItem(int position) {
        return list.get(position);
    }
 
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ListViewObject lvo;
        //여기에서 실제로 화면에 보여질 뷰를 리턴한다.
        if(view == null)
            lvo = new ListViewObject(context, list.get(position));
        else
            lvo = (ListViewObject) view;
 
        lvo.setImage(list.get(position).getDrawable());
        lvo.setText1(list.get(position).getText1());
        lvo.setText2(list.get(position).getText2());
 
        return lvo;
    }
 
    //List타입의 인스턴스 변수인 list에 데이터 추가
    public void addMakeItem(MakeItemInfo mii){
        list.add(mii);
    }
}
cs




activity_main.xml

화면에 보여질 액티비티 클래스가 호출하는 레이아웃 xml파일안에 <ListView>를 정의한다.

1
2
3
4
 <ListView
        android:id="@+id/mainListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
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
public class MainActivity extends AppCompatActivity {
 
    ListView mainListView;
    ListViewAdapter lvAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //activity_main 레이아웃 xml에서 ListView 뷰정보를 가져온다.
        mainListView = (ListView)findViewById(R.id.mainListView);
 
        //어댑터 확장 클래스의 인스턴스 생성. 생성자 파라미터에 이 액티비티 객체의 Cotext를 넘긴다.
        lvAdapter = new ListViewAdapter(this);
 
        Resources res = getResources();
 
        //어댑터의 인스턴스인 List타입의 변수에 모델 데이터 추가
        lvAdapter.addMakeItem(new MakeItemInfo(res.getDrawable(R.drawable.image1), "고양이들""첫번째"));
        lvAdapter.addMakeItem(new MakeItemInfo(res.getDrawable(R.drawable.image2), "보노보노""두번째"));
        lvAdapter.addMakeItem(new MakeItemInfo(res.getDrawable(R.drawable.image3), "고양이""세번째"));
 
        //ListView에 어댑터 확장 클래스 설정
        mainListView.setAdapter(lvAdapter);
        //ListView의 목록을 클릭 했을 때
        mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                MakeItemInfo mii = lvAdapter.getItem(position);
                Toast.makeText(MainActivity.this, mii.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
 
 
 
 
}
cs


'Android > 정리' 카테고리의 다른 글

그리기 객체  (0) 2016.09.19
안드로이드에서 서블릿을 호출하여 MySQL 질의 결과 가져오기  (0) 2016.09.08
키패드  (0) 2016.09.04
탭 (Tab)  (0) 2016.08.07
SeekBar  (0) 2016.08.04
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
more
Total
Today
Yesterday