본문 바로가기
App/Android Studio

Android Studio - ArrayList를 이용한 ListView 동적 생성

by 코젼 2022. 8. 4.
728x90
반응형

2022-08-04(33일차)


💡ArrayList를 이용하여 ListView 동적 생성하기

📃하단과 같이, ADD DATA 버튼을 누르면 ListView에 "data"라는 값이 추가되게 하시오


📝layout.xml

◾ xml파일 Design

<?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"
    android:orientation="vertical"
    android:id="@+id/ll">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="add data"
        android:id="@+id/btn"/>

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

</LinearLayout>

📝MainActivity.java

package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<String> al;
    ArrayAdapter<String> aa;

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

        al = new ArrayList<>();
        aa = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, al);

        ListView lv = findViewById(R.id.list);
        lv.setAdapter(aa);

        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                al.add("data");
                aa.notifyDataSetChanged();
            }
        });
    }
}

▪️ ArrayAdapter 객체를 생성할 때, 파라미터로 배열을 준다.

▪️ ArrayAdapter 객체 변수에 notifyDataSetChanged()함수를 사용해서 배열이 바뀜을 알려준다.

주의사항


📃사용자가 입력한 값을 OK버튼이 눌렀을 때 ListView의 Item이 추가되게 하시오


📝layout.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이름"
        android:id="@+id/tv_name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/tv_name"
        android:layout_alignBaseline="@id/tv_name"
        android:id="@+id/et_input"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CANCEL"
        android:layout_alignParentRight="true"
        android:layout_below="@id/et_input"
        android:id="@+id/btn_cancel"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK"
        android:layout_below="@id/et_input"
        android:layout_toLeftOf="@id/btn_cancel"
        android:id="@+id/btn_ok"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/btn_cancel"
        android:background="#c7f9c4"
        android:id="@+id/list"/>

</RelativeLayout>

 


📝MainActivity.java

package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.sql.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> al;
    ArrayAdapter<String> aa;

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

        al = new ArrayList<>();
        aa = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, al);

        ListView lv = findViewById(R.id.list);
        lv.setAdapter(aa);

        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText et = findViewById(R.id.et_input);
                String str = et.getText().toString();
                al.add(str);
                aa.notifyDataSetChanged();
            }
        });
    }
}

📃ListView의 해당 Item을 클릭할 때마다 Toast메시지가 표시되게 하시오

▪️ 리스너 연결 필수!


📝MainActivity.java

package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.sql.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> al;
    ArrayAdapter<String> aa;

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

        al = new ArrayList<>();
        aa = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, al);

        ListView lv = findViewById(R.id.list);
        lv.setAdapter(aa);
        lv.setOnItemClickListener(lis);

        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText et = findViewById(R.id.et_input);
                String str = et.getText().toString();
                al.add(str);
                aa.notifyDataSetChanged();
            }
        });
    }

    AdapterView.OnItemClickListener lis = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String str = al.get(position);
            Log.i("jyeon", "" + str);
            Toast.makeText(MainActivity.this, "" + str, Toast.LENGTH_SHORT).show();
        }
    };
}

 

▪️ Log의 msg, Toast의 text부분은 String형태이어야 하므로, ""를 추가해 문자열임을 나타낸다.

▪️ ArrayList의 get()함수를 이용하고, 매개변수 값으로 position을 주어 각 배열의 위치를 가져온다.


 

728x90
반응형

댓글