ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Android] ListView 리스트 만들고 데이터 저장하기
    Android 2022. 3. 9. 18:35

    activity_main.xml

    <?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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>

     

    MainActivity.java

    package com.example.listview;
    
    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; // ListView 클래스 생성 및 list 객체 선언
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            list = (ListView)findViewById(R.id.list); // ListView와 연결
    
            List<String> data = new ArrayList<>(); // string 받아 저장하는 list 생성
    
            //추가로 list와 listview 연결하는 어댑터 필요
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_list_item_1, data);// 레이아웃 고를 수 있음
            list.setAdapter(adapter); // 어댑터 세팅
    
            data.add("아잉");
            data.add("오잉");
            data.add("love");
            adapter.notifyDataSetChanged(); // 데이터 추가하여 이 상태로 저장하겠다
        }
    }

    실행 화면

    'Android' 카테고리의 다른 글

    [Android] SharedPreference; 데이터 임시 저장  (0) 2022.03.12
    [Android] Navigation menu  (0) 2022.03.12
    [Android] 패키지구조&역할  (0) 2022.03.09
    [Android] ImageView, Toast  (0) 2022.03.09
    [Android] Intent 화면전환  (0) 2022.03.09
Designed by Tistory.