티스토리 뷰

안드로이드 개발을 하다보면, 스크롤이 되면서 아이템들을 리스트로 보여줘야할 상황이 있다.

이것을 우리는 Adapter를 이용해서 data들을 가져오는 ListView를 사용할 것이다.


ArrayAdapter

- ArrayList(data)와 ListView(visual) 사이에 ArrayAdapter가 존재



1) data들을 ArrayList에 넣는다.

2) ArrayAdapter로 어떻게 보여줄지 지정한다.

3) 원하는 ListView에 보여준다.



Basic ArrayAdapter

ArrayAdapter itemsAdapter = 
new ArrayAdapter(this, android.R.layout.list_item, items);
아래 </string></string>은 무시해주세요.. ㅠ_ㅠ
parameter
  • activity instance (context)
  • XML item layout
  • array of data

위와 같이 ArrayAdpater를 초기화 해준 후, 아래처럼 ListView에 연결하여 채울 수 있다.
ListView listView = (ListView) findViewById(R.id.lvItems);
listView.setAdapter(itemsAdapter);

기본적으로 위의 코드는 각각의 데이터 항목들을 toString한 다음 

결과를 해당 데이터 항목의 행으로 표시되는 TextView의 값으로 할당하여 보기로 변환한다. 


Custom ArrayAdapter

ListView의 각 엔트리에 한개의 값만 넣지 않고 data를 customizing 하고 싶다면
custom ArrayAdapter를 만들어 사용하면 된다.

사용자의 name과 hometown을 넣고 싶다면 우선 아래와 같이 클래스를 만든다.
public class User {

	//declare private data instead of public to ensure the privacy of data field of each class
	private String name;
	private String hometown;

	public User(String name, String hometown) {
		this.name = name;
		this.hometown = hometown;
	}

	//retrieve user's name
	public String getName(){
		return name;
	}

	//retrieve users' hometown
	public String getHometown(){
		return hometown;
	}

	public static ArrayList getUsers() {
		ArrayList users = new ArrayList();
		users.add(new User("Harry", "San Diego"));
		users.add(new User("Marla", "San Francisco"));
		users.add(new User("Sarah", "San Marco"));
		return users;
	}
}


그 다음으로 각각의 아이템을 보여줄 XML 레이아웃을 만든다. 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
    <TextView
      android:id="@+id/tvName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Name" />
   <TextView
      android:id="@+id/tvHome"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="HomeTown" />
</LinearLayout>


그리고 Adapter를 정의하여 java객체를 view로 변환한다. (getView 메소드를 통해)

public class CustomUsersAdapter extends ArrayAdapter {
    public CustomUsersAdapter(Context context, ArrayList users) {
        super(context, 0, users);
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
           convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
        }

         // Get the data item for this position
         User user = getItem(position);

         // Lookup view for data population
        TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
        TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
        // Populate the data into the template view using the data object
        tvName.setText(user.getName());
        tvHome.setText(user.getHometown());
        // Return the completed view to render on screen
        return convertView;
    }
}

- getView() : ListView에서 하나의 row로 사용될 실제 view를 리턴한다.

- getItem() : 특정 position에 위치한 data들을 얻어온다.


마지막으로 정의했던 Adapter를 사용하고 ListView에 연결할 것이다.

public class CustomListActivity extends Activity {

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

	private void populateUsersList() {
		// Construct the data source
		ArrayList arrayOfUsers = User.getUsers();
		// Create the adapter to convert the array to views
		CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
		// Attach the adapter to a ListView
		ListView listView = (ListView) findViewById(R.id.lvUsers);
		listView.setAdapter(adapter);
	}
	
}


전체 코드와 참고 사이트는 아래에 링크 남겨두겠습니다.

https://github.com/codepath/android-custom-array-adapter-demo

https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함