앱 개발 공부방

안드로이드 스튜디오-List View 본문

Android-java

안드로이드 스튜디오-List View

춘행이 2020. 2. 7. 21:43
728x90

처음으로 xml으로 가서레이아웃을 LinearLayout으로(vertical) 바꾸어 주고 listview를 추가해줍니다

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

 그러면 아래 사진처럼 listview가 생성이 됩니다

다음으로 main으로 이동하여 코드를 추가합니다(설명은 주석)

package com.example.example3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView list;

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

        list=(ListView)findViewById(R.id.list);

        List<String> data=new ArrayList<>();//배열안에다 string형태로 list뷰에 넣는다는 뜻

        //리스트뷰랑 리스트를 연결하는 adapter생성
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,data);
        //simple_list_item_1을 기본으로 주어지는 listview디자인
        list.setAdapter(adapter);//list와 adapter연결

        data.add("춘행이");
        data.add("자바");
        data.add("리스트뷰");//데이터를 listview에 추가
        adapter.notifyDataSetChanged();//이 상태로 저장을 하겠다는 뜻
    }
}

실행결과

여기까지는 listview에 기본이었고 다음으로 아래사진 처럼 사진,제목,설명이 있는 커스텀 listview를 만들어 보겠습니다.

처음으로 listview에 넣을 사진을 drawable에 넣어주고 시작합니다

 

다음으로 listview칸에 사진은 어느 위치에 넣을지 제목 설명은 어느 위치에 넣을지를 정하는 xml파일을 만듭니다

res에 layout으로 가셔서 xml을 파일을 하나 만듭니다

 

xml-row

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:src="@drawable/apple"
        android:id="@+id/image"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="사과"
            android:textColor="#000"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_margin="5dp"
            android:id="@+id/textView1"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="사과는 빨간색"
            android:textColor="#000"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_margin="5dp"
            android:id="@+id/textView2"
            />




    </LinearLayout>


</LinearLayout>

이렇게 틀을 잡아주시고 main으로 돌아옵니다

java-MainActivity

package com.example.example3;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView list;
    String mTitle[]={"사과","바나나","수박","딸기","오렌지"};//listview에 title부분 설정
    String mDescription[]={"사과는 빨간색","바나나는 노란색","수박은 초록색","딸기는 빨간색","오렌지는 주황색"};//listview에 설명부분
    int images[]={R.drawable.apple,R.drawable.banana,R.drawable.watermelon,R.drawable.str,R.drawable.orange};
    //listview에 들어가는 사진

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

        list=(ListView)findViewById(R.id.list);

       MyAdapter adapter=new MyAdapter(this,mTitle,mDescription,images);
       list.setAdapter(adapter);//리스트에 어뎁터 설정

    }
    class MyAdapter extends ArrayAdapter<String>{

        Context context;
        String rTitle[];
        String rDescription[];
        int rImgs[];

        MyAdapter(Context c, String title[],String description[],int imgs[]){
            super(c,R.layout.row,R.id.textView1,title);
            this.context=c;
            this.rTitle=title;
            this.rDescription=description;
            this.rImgs=imgs;
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            //앞에서 만든 row xml파일을 view 객체로 만들기 위해서는 layoutInflater를 이용
            LayoutInflater layoutInflater=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row=layoutInflater.inflate(R.layout.row,parent,false);

            ImageView images=row.findViewById(R.id.image);
            TextView myTitle=row.findViewById(R.id.textView1);
            TextView myDescription=row.findViewById(R.id.textView2);

            images.setImageResource(rImgs[position]);
            myTitle.setText(rTitle[position]);
            myDescription.setText(rDescription[position]);


            return row;//앞에서 만든 xml 파일
        }
    }

}

xml-activity_main

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

실행결과

이렇게 커스텀listview가 완성됩니다

-만약 항목들이 많을시 main xml에 스크롤뷰를 추가해서 많은 항목들을 추가해서 볼수있습니다

728x90
Comments