ExpandableListView с адаптером, отображающий несколько текстовых представлений в одной строке представления списка - PullRequest
0 голосов
/ 11 ноября 2019

Я использую Kotlin для описания ExpendableListview во Fragemnt. Я хочу показать несколько текстовых представлений в одной строке представления списка, и я поместил все свои элементы в массив. Первая позиция для названия продуктов питания Вторая позиция для бренда продуктов питания Третья позиция для калорий в продуктах питания Четвертая позиция для подачи продуктов питания Четыре элемента в группе. Я пробовал Google для ExpendableListview, но все статьи для одного tetview в той же строке.

Код, показанный ниже: Fragment.kt Ниже

class FoodFragment : Fragment() {
    // Global Declare Below
    private var list4Breakfast = ArrayList<String>()
    private var list4Lunch = ArrayList<String>()
    private var list4Dinner = ArrayList<String>()
    private var list4Other = ArrayList<String>()
    private lateinit var date:String
    // Start OnCreateView
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_food, container, false)
        //Add Button
        var btnAdd = root.findViewById<Button>(R.id.btn_addfood)
        btnAdd.setOnClickListener {
            val intent = Intent(activity, RecordingActivity::class.java)
            startActivity(intent)
        }
        //Default The Date
        val dateText = root.findViewById<EditText>(R.id.et_todaydate)
        var sdf = SimpleDateFormat("yyyy-M-dd")
        var currentDate = sdf.format(Date())
        dateText.setText(currentDate)
        //Date Edit Text
        val c = Calendar.getInstance()
        val y = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)
        val dpd = DatePickerDialog(
            activity,
            DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
                dateText.setText("" + year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)
            },
            y,
            month,
            day
        )
        dateText.isClickable = true
        dateText.showSoftInputOnFocus = false
        dateText.setOnClickListener {
            dpd.show()
        }
        date = dateText.text.toString()
        readDate()
        var elv = root.findViewById<ExpandableListView>(R.id.elv_meal)
        val meal = listOf("Breakfirst", "Lunch", "Dinner", "Other")
        var food = listOf(
            list4Breakfast,
            list4Lunch,
            list4Dinner,
            list4Other
        )
        Log.d("Data Pushing", food.toString())
        val adapter = FoodAdapter(
            activity,
            meal,
            food
        )
        elv.setAdapter(adapter)

        return root
    }
    private fun  readDate(){
        var db = FirebaseFirestore.getInstance()
        var tag = "Database Ref"
        var uid = FirebaseAuth.getInstance().currentUser!!.uid
        //Breakfast
        db.collection("RecordOf$uid").document(date).collection("Breakfirst").get()
            .addOnSuccessListener { reslut ->
                for (document in reslut) {
                    list4Breakfast.add(document.get("foodName").toString())
                    list4Breakfast.add(document.get("brand").toString())
                    list4Breakfast.add(document.get("calories").toString())
                    list4Breakfast.add(document.get("serving").toString())

                }
            }.addOnFailureListener { exception ->
                Log.d(
                    tag,
                    "Error getting documents: ",
                    exception
                )
            }
        //Lunch

        db.collection("RecordOf$uid").document(date).collection("Lunch").get()
            .addOnSuccessListener { reslut ->
                for (document in reslut) {
                    list4Lunch.add(document.get("foodName").toString())
                    list4Lunch.add(document.get("brand").toString())
                    list4Lunch.add(document.get("calories").toString())
                    list4Lunch.add(document.get("serving").toString())
                }
            }.addOnFailureListener { exception ->
                Log.d(
                    tag,
                    "Error getting documents: ",
                    exception
                )
            }
        //Dinner

        db.collection("RecordOf$uid").document(date).collection("Dinner").get()
            .addOnSuccessListener { reslut ->
                for (document in reslut) {
                    list4Dinner.add(document.get("foodName").toString())
                    list4Dinner.add(document.get("brand").toString())
                    list4Dinner.add(document.get("calories").toString())
                    list4Dinner.add(document.get("serving").toString())
                }
            }.addOnFailureListener { exception ->
                Log.d(
                    tag,
                    "Error getting documents: ",
                    exception
                )
            }
        //Other

        db.collection("RecordOf$uid").document(date).collection("Other").get()
            .addOnSuccessListener { reslut ->
                for (document in reslut) {
                    list4Other.add(document.get("foodName").toString())
                    list4Other.add(document.get("brand").toString())
                    list4Other.add(document.get("calories").toString())
                    list4Other.add(document.get("serving").toString())
                }
            }.addOnFailureListener { exception ->
                Log.d(
                    tag,
                    "Error getting documents: ",
                    exception
                )
            }
    }
}

Адаптер ниже

class FoodAdapter(
    private val context: FragmentActivity?,
    private val meal: List<String>,
    private val food: List<List<String>>

) : BaseExpandableListAdapter() {


    override fun getGroup(groupPosition: Int): Any {
        return meal[groupPosition]
    }

    override fun getChild(groupPosition: Int, childPosition: Int): Any {
        if (childPosition%4 == 0) {
            return food[groupPosition][childPosition]
        }
        return -1
    }

    override fun getGroupCount(): Int {
        return meal.size
    }

    override fun getChildrenCount(groupPosition: Int): Int {
        return (food[groupPosition].size / 4)
    }

    override fun getGroupId(groupPosition: Int): Long {
        return groupPosition.toLong()
    }

    override fun getChildId(groupPosition: Int, childPosition: Int): Long {
        return (groupPosition * 100 + childPosition).toLong()
    }

    override fun hasStableIds(): Boolean {
        return true
    }

    override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
        return true
    }

    override fun getGroupView(
        groupPosition: Int,
        isExpanded: Boolean,
        convertView: View?,
        parent: ViewGroup?
    ): View {
        val view =
            convertView ?: LayoutInflater.from(context).inflate(R.layout.food_group_item, null)
        val textView = view.findViewById<TextView>(R.id.txtDepartmentName)
        textView.text = meal[groupPosition]
        return view
    }

    override fun getChildView(
        groupPosition: Int,
        childPosition: Int,
        isLastChild: Boolean,
        convertView: View?,
        parent: ViewGroup?
    ): View {
        val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.list_food, null)
        var foodName = view.findViewById<TextView>(R.id.foodName)
        var brand = view.findViewById<TextView>(R.id.brand)
        var calories = view.findViewById<TextView>(R.id.calories)
        var serving = view.findViewById<TextView>(R.id.serving)
        foodName.text = food[groupPosition][childPosition + 0]
        brand.text = food[groupPosition][childPosition + 1]
        calories.text = food[groupPosition][childPosition + 2]
        serving.text = food[groupPosition][childPosition + 3]
        return view
    }
}

Пользовательский интерфейс Listview

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextView
        android:id="@+id/foodName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textStyle="bold"
        android:textColor="@android:color/black"
        android:text="TextView"
        tools:layout_editor_absoluteX="58dp"
        tools:layout_editor_absoluteY="94dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/brand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="40dp"
        android:text="TextView"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

 -

    <TextView
        android:id="@+id/calories"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:layout_marginTop="40dp"
        android:text="TextView"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/brand"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/serving"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:layout_marginTop="40dp"
        android:text="TextView"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/calories"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Desgin of Each Row

...