투케이2K

392. (android/java) choice listView 동적으로 목록 추가, 삭제 수행 리스트 뷰 생성 - adapter.notifyDataSetChanged 본문

Android

392. (android/java) choice listView 동적으로 목록 추가, 삭제 수행 리스트 뷰 생성 - adapter.notifyDataSetChanged

투케이2K 2022. 11. 4. 18:56
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

 

[Java : 소스 코드]

public class MainActivity extends AppCompatActivity {


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

        // [빈 배열 생성]
        final ArrayList<String> items = new ArrayList<String>();


        // [ArrayAdapter 생성] : 리스트 View 는 single choice 지정
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, items) ;


        // [listview 생성 및 adapter 지정]
        final ListView listview = (ListView) findViewById(R.id.listview1);
        listview.setAdapter(adapter);


        // [동적으로 목록 추가 실시]
        Button addButton = (Button)findViewById(R.id.add);
        addButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {

                int count;
                count = adapter.getCount();

                // 아이템 추가
                items.add("LIST" + Integer.toString(count + 1));

                // listview 갱신
                adapter.notifyDataSetChanged();
            }
        });


        // [동적으로 목록 삭제 실시]
        Button deleteButton = (Button)findViewById(R.id.delete);
        deleteButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {

                int count, checked;
                count = adapter.getCount();

                if (count > 0) {

                    // 현재 선택된 아이템의 position 획득
                    checked = listview.getCheckedItemPosition();

                    if (checked > -1 && checked < count) {
                        // 아이템 삭제
                        items.remove(checked) ;

                        // listview 선택 초기화
                        listview.clearChoices();

                        // listview 갱신
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }) ;

    }

}
 

[Xml : 소스 코드]

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"

        android:choiceMode="singleChoice" />
 

[결과 출력]

 

 

반응형
Comments