Как добавить события щелчка на холст в JetPack Compose

#android #android-jetpack-compose

Вопрос:

Я использовал Canvas в Compose для определения линейной диаграммы. введите описание изображения здесь

Я хочу указать события щелчка для точек на линейном графике, но я не нашел соответствующей информации для решения проблемы.

Пожалуйста, предоставьте некоторые интересные идеи или соответствующую информацию.

Ответ №1:

Мое предложение было бы примерно таким:

 // First, you must keep track the position of the points
// and their respective sizes using a list of Rect 
val dotRects = ArrayList<Rect>()
// e.g.: 
// dotRects.add(Rect(top = 0f, left = 0f, bottom = 40f, right = 40f))
Canvas(
    modifier = Modifier
        // other modifiers...
        .pointerInput(Unit) {
            detectTapGestures(
                onTap = { tapOffset ->
                    // When the user taps on the Canvas, you can 
                    // check if the tap offset is in one of the
                    // tracked Rects.
                    var index = 0
                    for (rect in dotRects) {
                        if (rect.contains(tapOffset)) {
                            // Handle the click here and do 
                            // some action based on the index
                            break // don't need to check other points, 
                                  // so break
                        }
                        index  
                    }
                }
            )
        }
) {
   // Your chart...
}
 

Комментарии:

1. большое вам спасибо, я попробую . желаю вам счастливой жизни.