Reputation: 1322
I'm trying to implement a simple pie chart using MPAndroidChart, I want the simplest example possible, I want to display it into a fragment, the problem is that the chart is not being redered but the labels are showed in an strange way as we can see in the next screen shot:
This is the code:
class StatsFragment : Fragment() {
lateinit var debtsChart : PieChart
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_stats, container, false)
debtsChart = v.findViewById(R.id.debtsPieChart)
setupPieChart()
return v;
}
private fun setupPieChart() {
// Populating a list of PieEntries
val rainFall : FloatArray = floatArrayOf(98.5f,128.8f,161.6f)
val monthNames : Array<String> = arrayOf("Jan", "Fab", "Mar")
val pieEntries = ArrayList<PieEntry>()
for(a in 1..2){
pieEntries.add(PieEntry(rainFall[a],monthNames[a]))
}
val dataSet = PieDataSet(pieEntries,"Hello world")
val data = PieData(dataSet)
debtsChart.data = data
debtsChart.invalidate()
}
And this is the xml for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorActivityBackground">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/detalles_de_deuda_global"
android:textColor="@android:color/black"
android:textSize="@dimen/title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/debtsPieChart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
Upvotes: 0
Views: 794
Reputation: 610
Just add fillViewPort = "true"
to ScrollView to make ConstraintLayout taking all the place on your screen. Cause in the way you made it, the PieChart depends on the sizes of the ConstraintLayout and vice versa. To make everything works properly either must be given a certain height for your chart, or you have to allow ScrollView to take all the place on the screen.
PS: I'd not recommend doing something with a layout in fragment before it is actually created. You can do the same after onViewCreated()
is called.
Upvotes: 1