ListArray
package com.example.choi.ex02;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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;
import java.util.List;
public class ListArray extends AppCompatActivity {
//1.위젯 선언
ListView list;
List<String> items;
Button button1;
EditText edit1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mlistarray);
//2.리소스 연결
list=(ListView)findViewById(R.id.list);
button1=(Button)findViewById(R.id.button1);
edit1=(EditText)findViewById(R.id.edit1);
//3.리스트 구성
items=new ArrayList<String>();
items.add("사과");
items.add("포도");
items.add("파인애플");
items.add("체리");
items.add("자두");
//4. 아답터 생성 ( 리스트데이터 => 아답터 => 리스트 뷰)
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
//5. 리스트뷰에 아답터를 연결시킴
list.setAdapter(adapter);
//6. 버튼 클릭 이벤트
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// EditText 에 입력된 값
String str =edit1.getText().toString();
items.add(str); //ArrayList에 추가
//아답터 갱신
adapter.notifyDataSetChanged();
edit1.setText("");
}
});
//7. 리스트뷰의 롱클릭 이벤트
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//롱클릭한 아이템 제거
items.remove(position);
//아답터 갱신
adapter.notifyDataSetChanged();
return ;
}
});
}
}
mlistarray.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="100dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="@+id/edit1"
android:layout_weight="1" />
<Button
android:text="확인"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_marginTop="100dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:layout_width="match_parent"
android:layout_height="365dp"
android:id="@+id/list" />
</LinearLayout>
</RelativeLayout>
댓글 ( 4)
댓글 남기기