ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] CustomView 예제 2
    Android/공부 2020. 5. 26. 19:11
    어댑터 리스트로 날씨 어플 만들기

     

     

     

    1. xml

    1. item_weather.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="4dp">
    
        <ImageView
            android:id="@+id/weatherimage"
            android:layout_width="90dp"
            android:layout_height="90dp"
            app:srcCompat="@mipmap/ic_launcher" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_gravity="center"
            android:padding="2dp">
            <TextView
                android:id="@+id/citytext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="도시명"
                android:textStyle="bold"
                android:textSize="20dp"/>
            <TextView
                android:id="@+id/temptext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="기온"
                android:textColor="@android:color/darker_gray"
                android:textSize="16dp"
                android:layout_gravity="right"/>
        </LinearLayout>
    </LinearLayout>
    • 이미지뷰와 텍스트뷰로 구성된 레이아웃을 설정한다.

       

     

    2. activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/item_weather"/>
    </LinearLayout>
    • ListView 를 추가해 item_weather.xml 파일과 연결한다.

     

     


     

    2. java

    1. Weather.java ( 모델 클래스)

    public class Weather {
        String city;
        String temp;
        String Weather;
    • 클래스에 필요한 멤버 변수들을 선언한다.

     

    public Weather(String city, String temp, String weather) {
            this.city = city;
            this.temp = temp;
            Weather = weather;
        }
    
        public String getCity() {
            return city;
        }
    
        public void setCity(String city) {
            this.city = city;
        }
    
        public String getTemp() {
            return temp;
        }
    
        public void setTemp(String temp) {
            this.temp = temp;
        }
    
        public String getWeather() {
            return Weather;
        }
    
        public void setWeather(String weather) {
            Weather = weather;
        }
    
        @Override
        public String toString() {
            return "Weather{" +
                    "city='" + city + '\'' +
                    ", temp='" + temp + '\'' +
                    ", Weather='" + Weather + '\'' +
                    '}';
        }
    • 생성자나 getter setter, toString 등 필요한 것들을 오버라이딩 해서 사용한다.

     

     

    2. MyFirstAdapter.java ( 어댑터 클래스 ) 

    private List<Weather> mData;
        private Map<String, Integer> mWeatherImageMap;
    
        public MyFirstAdapter(List<Weather> mData) {
            this.mData = mData;
            mWeatherImageMap = new HashMap<>();
            mWeatherImageMap.put("맑음", R.drawable.sunny);
            mWeatherImageMap.put("폭설", R.drawable.blizzard);
            mWeatherImageMap.put("구름", R.drawable.cloudy);
            mWeatherImageMap.put("비", R.drawable.rainy);
            mWeatherImageMap.put("눈", R.drawable.snow);
        }
    • 어댑터에 리스트를 추가하고 날씨 이미지를 넣어준다.

     

    • 어댑터 클래스는 BaseAdapter 클래스를 상속받는다.

    • 코드에 빨간 줄이 뜨면 필요한 메소드를 오버라이딩 시켜준다.

    public class MyFirstAdapter extends BaseAdapter {
    ...
    @Override
        public int getCount() {
            return mData.size();
        }
    
        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

     

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            Weather weather = mData.get(position);
    
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_weather, parent, false);
    
                //날씨, 도시, 기온 View
                ImageView weatherimage =(ImageView) convertView.findViewById(R.id.weatherimage);
                TextView citytext = convertView.findViewById(R.id.citytext);
                TextView temptext = convertView.findViewById(R.id.temptext);
    
                holder.weatherimage = weatherimage;
                holder.citytext = citytext;
                holder.temptext = temptext;
    
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
    
            // 데이터 설정 -> 홀더에 저장
            holder.citytext.setText(weather.getCity());
            holder.temptext.setText(weather.getTemp());
            holder.weatherimage.setImageResource(mWeatherImageMap.get(weather.getWeather()));
    
            return convertView;
        }
    private class ViewHolder {
            ImageView weatherimage;
            TextView citytext;
            TextView temptext;
        }
    • 앞에 작성했던 레이아웃은 getView() 안에서  데이터를 설정한다. 

     

     

    3. MainActivity.java ( 메인 클래스 ) 

    package com.example.myadaptiveviewex;
    
    import ...
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final ArrayList<Weather>  data = new ArrayList<>();
            data.add(new Weather("수원", "25도", "맑음"));
            data.add(new Weather("서울", "26도", "비"));
            data.add(new Weather("안양", "24도", "구름"));
            data.add(new Weather("부산", "29도", "구름"));
            data.add(new Weather("인천", "23도", "맑음"));
            data.add(new Weather("대구", "28도", "비"));
            data.add(new Weather("용인", "25도", "비"));
    
            MyFirstAdapter adapter = new MyFirstAdapter(data);
    
            ListView listView = findViewById(R.id.listView);
            listView.setAdapter(adapter);
    
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Weather item = data.get(position);
                    Toast.makeText(getApplicationContext(),
                            item.getCity()+ " " +item.getTemp(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    • 날씨에 관한 데이터를 추가하고 리스트뷰와 어댑터를 연결한다.

    • 리스트뷰 아이템 클릭 이벤트를 작성하고 모뎀 클래스에 만들었던 생성자를 이용해 리스트의 데이터를 받아올 수 있다.

     

     

    댓글

Designed by Tistory.