Adapter, GridView와 ListView 적용법
2019. 11. 25. 14:56
Programing/Android
1. List VIew
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
ListView lv;
TextView tv;
ArrayAdapter<String> adapter;
String[] list = {"Apple", "Orange", "Melon", "Lemon"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
tv = (TextView) findViewById(R.id.textview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String fruit = list[position];
tv.setText(fruit);
}
2. GridView
GridView
public class MainActivity extends AppCompatActivity {
List<String> cityNames;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityNames = new ArrayList<String>(); // 데이터 준비
cityNames.add("서울특별시");
cityNames.add("부산광역시");
cityNames.add("대구광역시");
cityNames.add("인천광역시");
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cityNames); // 어댑터를 생성
GridView gridView = (GridView) findViewById(R.id.gridView); // 어댑터를 설정
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // 항목 클릭시 위치값과 지역명 토스트로 출력
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view.findViewById(android.R.id.text1);
Toast.makeText(MainActivity.this, position + ", " + tv.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
'Programing > Android' 카테고리의 다른 글
Android 리스트뷰 (0) | 2019.12.28 |
---|---|
assets 사전 insert DB (0) | 2019.12.09 |
FCM 앱 알람 (0) | 2019.11.02 |
커스텀 토스트, 커스텀 다이얼로그 (0) | 2019.10.23 |
배열과 테이블 위젯 이용한 계산기, 숫자버튼 예제 (0) | 2019.10.21 |