CardView не активируется - PullRequest
0 голосов
/ 06 мая 2019

В MainActivity у меня есть круговая диаграмма, откуда библиотека получает от GitHub - PhilJay / MPAndroidChart: мощное представление диаграммы Android .Я добавляю круговую диаграмму в cardView. При нажатии cardView предполагается отображение toast.Но onClickListener вообще не работает.

MainActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        showChart()

        cardView.setOnClickListener {
            Toast.makeText(application,"clicked",Toast.LENGTH_LONG).show()
        }
    }

    private fun showChart() {

        chart.setUsePercentValues(true)
        chart.description.isEnabled = false
        chart.center
        chart.extraRightOffset = 20f

        chart.isDrawHoleEnabled = true
        chart.setHoleColor(Color.WHITE)

        chart.setTransparentCircleColor(Color.WHITE)
        chart.setTransparentCircleAlpha(10)

        chart.holeRadius = 58f
        chart.transparentCircleRadius = 46f

        chart.setDrawCenterText(true)

        chart.rotationAngle = 0f
        chart.isRotationEnabled = true
        chart.animateY(1400, Easing.EaseInOutQuad)

        val l = chart.legend
        l.verticalAlignment = Legend.LegendVerticalAlignment.CENTER
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.VERTICAL
        l.setDrawInside(false)
        l.xOffset = 50f

        chart.setEntryLabelColor(Color.WHITE)
        chart.setEntryLabelTextSize(12f)
        setData(3,5)
    }

    private fun setData(numOpen: Int, numInProgress: Int) {
        val entries = ArrayList<PieEntry>()
        val colors = ArrayList<Int>()

        if (numOpen > 0) {
            entries.add(PieEntry(numOpen.toFloat(), "Open"))
            colors.add(ColorTemplate.rgb("#F44336"))

        }
        if (numInProgress > 0) {
            entries.add(PieEntry(numInProgress.toFloat(), "Progress"))
            colors.add(ColorTemplate.rgb("#2196F3"))
        }

        val dataSet = PieDataSet(entries, "Status")

        dataSet.sliceSpace = 3f
        dataSet.iconsOffset = MPPointF(0f, 40f)
        dataSet.selectionShift = 5f

        dataSet.colors = colors


        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter(chart))
        data.setValueTextSize(11f)
        data.setValueTextColor(Color.WHITE)
        chart.data = data

        // undo all highlights
        chart.highlightValues(null)
        chart.invalidate()
    }
}

main_activity

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        <android.support.v7.widget.CardView
                android:id="@+id/cardView"
                android:clickable="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="15dp"
                android:layout_marginRight="15dp">

            <com.github.mikephil.charting.charts.PieChart
                    android:background="@color/colorPrimary"
                    android:id="@+id/chart"
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:layout_gravity="center_horizontal|center_vertical"/>

        </android.support.v7.widget.CardView>
    </LinearLayout>
</ScrollView>

Изображение

enter image description here

1 Ответ

0 голосов
/ 06 мая 2019

Поскольку PieChart полностью поглощает click для взаимодействия с элементами диаграммы, прослушиватель щелчков, определенный в родительском элементе, вызываться не будет. Даже если вы установите OnClickListener на PieChart, оно не будет работать. Решением этой проблемы является установка onChartGestureListener в PieChart и вызов вашего метода из onChartSingleTapped.

Пример

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    cardView.setOnClickListener {
        doThis();
    }

    chart.onChartGestureListener = object : OnChartGestureListener {
        override fun onChartSingleTapped(me: MotionEvent?) {
            doThis()
        }
    }
}

fun doThis(){
    // your code goes here
}

...