3월 21일

오늘 배운 것

  • TODO 프로젝트로 TODO App만들기(10) 完

Chart 만들기

Chart

chart만들기위해서 라이브러리를 다운로드 해야함

implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

++ 추가적으로 추가해주어야 에러가 생기지 않는다.

maven { url 'https://jitpack.io' }

Chart를 관리할 Fragment 만들기

  • viewPager 기능 사용
    viewPager는 화면을 scroll했을 때 옆으로 부드럽게 넘어가는 액션을 말함
    유사한 화면을 연속해서 보여 줄 때 좋음
    탭은 변화가 없어서 Pager로 넘어갈 때 탭도 화면에 맞춰서 같이 선택되는 메소드를 넣어줘야 함
package com.example.todo.fragment.todo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.todo.R;
import com.example.todo.fragment.chart.BarChartFragment;
import com.example.todo.fragment.chart.PieChartFragment;
import com.github.mikephil.charting.charts.BarChart;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class TodoChartFragment extends Fragment {
    public static final String TAG = "TodoChartFragment";

    private TabLayout.Tab tab1, tab2;
    private ViewPager viewPager;
    private BarChartFragment barChartFragment;
    private PieChartFragment pieChartFragment;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_todo_chart, container, false);

        // 뷰 참조 가져오기
        TabLayout tabLayout = view.findViewById(R.id.tabs);
        viewPager = view.findViewById(R.id.viewPager);

        // 탭 생성해서 추가
        tab1 = tabLayout.newTab().setText("원형 차트");
        tab2 = tabLayout.newTab().setText("막대 차트");

        // 탭 레이아웃에 탭 추가하기
        tabLayout.addTab(tab1);
        tabLayout.addTab(tab2);

        // 탭레이아웃에 탭선택 이벤트 연결하기
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition(); // TabLayout에 추가된 순서, 0부터 시작함

//               if (position == 0) {
//                   viewPager.setCurrentItem(0);
//                   pieChartFragment.animaetChart();
//               } else if (position == 1) {
//                   viewPager.setCurrentItem(1);
//                   barChartFragment.animaetChart();
//               }
                viewPager.setCurrentItem(position);
            }


			// 선택이 안됬을 때
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }
			// 다시 선택 됬을 때
            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        // 뷰페이저의 캐시기능, 미리 페이지를 준비를 해놔서 쾌적하게 이용가능
        viewPager.setOffscreenPageLimit(2);

        MyPagerAdapter pagerAdapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());

        barChartFragment = new BarChartFragment();
        pieChartFragment = new PieChartFragment();

        pagerAdapter.addItem(pieChartFragment);
        pagerAdapter.addItem(barChartFragment);

        viewPager.setAdapter(pagerAdapter);

        // 뷰 페이저에 페이지변경 이벤트 연결하기
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 넘기는 중일 때
            }

            @Override
            public void onPageSelected(int position) {
                // 넘겨서 페이지가 선택 됬을 때
                if (position == 0) {
                    tabLayout.selectTab(tab1);
                } else if (position == 1) {
                    tabLayout.selectTab(tab2);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


       return view;
    }// onCreateView

    class MyPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> items = new ArrayList<>();

        public MyPagerAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return items.get(position);
        }

        @Override
        public int getCount() {
            return items.size();
        }

        public  void addItem(Fragment item) {
            items.add(item);
        }// class MyPagerAdapter
    } // MyPagerAdapter
}// class TodoChartFragment

Pie Chart 만들기

package com.example.todo.fragment.chart;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.todo.R;
import com.example.todo.retrofit.RetrofitClient;
import com.example.todo.retrofit.TodoService;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PieChartFragment extends Fragment {

    public static final String TAG = "PieChartFragment";
    private PieChart pieChart;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pie_chart, container, false);

        // 차트 뷰 참조 가져오기
        pieChart = view.findViewById(R.id.pieChart);

        // 서버로 부터 차트 데이터 가져오기 요청
        requestChartData();

        return view;
    }

    private void requestChartData() {
        TodoService todoService = RetrofitClient.getTodoService();
        Call<List<Map<String, Object>>> call = todoService.getStatusPerCount("statusPerCount");

        call.enqueue(new Callback<List<Map<String, Object>>>() {
            @Override
            public void onResponse(Call<List<Map<String, Object>>> call, Response<List<Map<String, Object>>> response) {
                if (!response.isSuccessful()) {
                    Log.d(TAG, "onResponse : " + response.message());
                    return;
                }
                List<Map<String, Object>> mapList = response.body();
                setChartDataAndShow(mapList);
            }

            @Override
            public void onFailure(Call<List<Map<String, Object>>> call, Throwable t) {
                Log.d(TAG, "onFailure : " + t.getMessage());
            }
        });
    }//requestChartData

    private void setChartDataAndShow(List<Map<String, Object>> mapList) {
        // 차트 데이터 준비
        List<PieEntry> pieEntries = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            String status = (String) map.get("status");
            double count = (Double) map.get("count");

            pieEntries.add(new PieEntry((float) count, status));
        } // for

        PieDataSet pieDataSet = new PieDataSet(pieEntries, "완료여부 별 갯수");
        pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        pieDataSet.setValueTextColor(Color.BLACK);
        pieDataSet.setValueTextSize(16f);

        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
        pieChart.getDescription().setEnabled(false);
        pieChart.setCenterText("완료여부 별 갯수");
        pieChart.animateXY(0,0);
    }// setChartDataAndShow

    public void animaetChart() {
        pieChart.animateXY(0,0);
    }
}// class PieChartFragment

Bar Chart만들기

package com.example.todo.fragment.chart;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.todo.R;
import com.example.todo.domain.User;
import com.example.todo.retrofit.RetrofitClient;
import com.example.todo.retrofit.TodoService;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BarChartFragment extends Fragment {
    public static final String TAG = "BarChartFragment";
    private BarChart barChart;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bar_chart, container, false);

        // 차트 뷰 참조 가져오기
        barChart = view.findViewById(R.id.barChart);

        // 서버로 부터 차트 데이터 가져오기 요청
        requestChartData();

        return view;
    }
    private void requestChartData() {
        TodoService todoService = RetrofitClient.getTodoService();
        Call<List<User>> call = todoService.getUsernamePerCount("getUsernamePerCount");

        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (!response.isSuccessful()) {
                    Log.d(TAG, "onResponse : " + response.message());
                    return;
                }
                List<User> userList = response.body();
                setChartDataAndShow(userList);
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Log.d(TAG, "onFailure : " + t.getMessage());
            }
        });

    }//requestChartData

    private void setChartDataAndShow(List<User> userList) {
        // 차트 데이터 준비
        List<BarEntry> barEntries = new ArrayList<>();

        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);

            String username = user.getUserName();
            float todoCount = user.getTodoCount();

            barEntries.add(new BarEntry(i, todoCount, username));
        } // for
        BarDataSet barDataSet = new BarDataSet(barEntries,"사용자 아이디 별 할일 갯수");
        barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        barDataSet.setValueTextColor(Color.BLACK);
        barDataSet.setValueTextSize(16f);

        BarData barData = new BarData(barDataSet);

        barChart.setFitBars(true);
        barChart.setData(barData);
        barChart.getDescription().setText("사용자아이디 별 할일 갯수");
        barChart.animateY(0);

    }// setChartDataAndShow

    public void animaetChart() {
        barChart.animateY(0);
    }
}// class BarChartFragment

참고사이트
https://aries574.tistory.com/118



시간 부족으로 인해 모든 기능 구현을 못 함, 이 뒤로는 각자 알아서 완성해보기

좋은 웹페이지 즐겨찾기