1)
2)
3)
package kr.android.s26listviewdemo04;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<MyItem> arItem;
ListView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arItem = new ArrayList<MyItem>();
arItem.add(new MyItem(R.mipmap.ic_launcher,"삼성 노트북"));
arItem.add(new MyItem(R.mipmap.ic_launcher,"LG 에어컨"));
arItem.add(new MyItem(R.mipmap.ic_launcher,"현대 소나타"));
//MyListAdapter 생성
MyListAdapter myAdapter = new MyListAdapter(this,R.layout.widget_icontext,arItem);
//ListView에 MyListAdapter 등록
myList = (ListView)findViewById(R.id.list);
myList.setAdapter(myAdapter);
}
}
//리스트 뷰에 출력할 항목
class MyItem{
int icon;
String name;
MyItem(int icon,String name){
this.icon = icon;
this.name = name;
}
}
//커스텀 어댑터 클래스
class MyListAdapter extends BaseAdapter {
Context context;
ArrayList<MyItem> alist;
int layout;
LayoutInflater inflater;
public MyListAdapter(Context context, int layout, ArrayList<MyItem> alist){
this.context = context;
this.layout = layout;
this.alist = alist;
//ListView에서 사용할 view를 정의한 xml을 읽어오기 위해 LayoutInflater 객체 생성
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return alist.size();
}
@Override
public Object getItem(int position) {
return alist.get(position).name;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
final int pos = position;
if(view == null){
view = inflater.inflate(layout,null);
}
ImageView img = (ImageView)view.findViewById(R.id.img);
img.setImageResource(alist.get(position).icon);
TextView text = (TextView)view.findViewById(R.id.text);
text.setText(alist.get(position).name);
Button btn = (Button)view.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
String str = alist.get(pos).name + "를 주문합니다.";
Toast.makeText(context,str,Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
반응형
'IT > Android Studio' 카테고리의 다른 글
s34ViewFilpperTouchDemo 터치 슬라이드 애니메이션으로 다음사진 보기 (0) | 2020.07.03 |
---|---|
s33ViewFilpperDemo 갤러리 다음사진 보기 (0) | 2020.07.03 |
Android Studio s25ListViewDemo03 (삭제 기능 ) (0) | 2020.07.02 |
Android Studio s24ListViewDemo02 (ArrayList을 이용한 ListView) (0) | 2020.07.02 |
Android Studio s23ListViewDemo01 (배열을 이용한 ListView) (0) | 2020.07.02 |