Shafi
Shafi

Reputation: 1368

how to display legend on right side of piechart in achartengine android

I am using the pie chart view from achartengine's tutorial. Here is what i want.

enter image description here

I want the legends i.e. pass/fail to be displayed to the right of the pie chart as shown in the figure. In the demo examples of achartengine, they are bottom aligned. How to get them to the right? Please help!

Upvotes: 4

Views: 2088

Answers (1)

Patito00Game
Patito00Game

Reputation: 1

This code below worked for me. But I think it's better creating a RecyclerView as a legend, instead of using the one provided by MPAndroidChart class. What I did:

  1. Create the RecyclerView and celda_recycler_legend.xml:
  2. Create an AdapterLegend.java script, which extents RecyclerView.Adapter class, to be able to use a RecyclerView with the legends. On this script, I added a LegendViewHolder instance, which extents RecyclerView.ViewHolder, with the celda_recycler_legend.xml configured.

AdapterLegend

 class AdapterLegend extends RecyclerView.Adapter {

    private ArrayList<String> legends;
    private ArrayList<Integer> colors;

    public AdapterLegend(ArrayList legends, ArrayList<Integer> colors) {
        this.legends = legends;
        this.colors = colors;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        return new LegendViewHolder(layoutInflater.inflate(R.layout.celda_recycler_legend, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        LegendViewHolder legendViewHolder = (LegendViewHolder) holder;
        legendViewHolder.LoadLegend(legends.get(position), colors.get(position));
    }

    @Override
    public int getItemCount() { return legends.size(); }
  }

LegendViewHolder

class LegendViewHolder extends RecyclerView.ViewHolder {

    private final TextView legendText;
    private final ImageView legendColorLabel;

    public LegendViewHolder(@NonNull View itemView) {
        super(itemView);

        legendText = itemView.findViewById(R.id.legendTextView);
        legendColorLabel = itemView.findViewById(R.id.legendLabelColor);
    }

    public void LoadLegend(String legend, int legendColor){
        legendText.setText(legend);
        legendColorLabel.setBackgroundColor(legendColor);
    }
}
  1. I set the RecyclerView with an AdapterLegend instance

       legendRecyclerView = recountDataLayout.findViewById(R.id.chartLegendRecycler);
       legendRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
    

https://github.com/PhilJay/MPAndroidChart/issues/2478#issuecomment-378566623

Hope this works for you!

Upvotes: 0

Related Questions