IT/Android

android - Adapter, ListView, arraylist 항목추가, 삭제

노마드오브 2018. 11. 10. 22:31
package com.example.it.myapplication9_2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

final ArrayList<String> midList = new ArrayList<>();
ListView list = (ListView) findViewById(R.id.listView1);

final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, midList);
list.setAdapter(adapter);

final EditText edtItem = (EditText) findViewById(R.id.editItem);
Button btnAdd = (Button) findViewById(R.id.btnAdd);

btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
midList.add(edtItem.getText().toString());
adapter.notifyDataSetChanged();
}
});

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
midList.remove(position);
adapter.notifyDataSetChanged();
}
});

}
}


<?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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/editItem"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>

<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dddddd"
android:text="항목 추가" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>

</LinearLayout>