Нерабочие элементы после добавления Layout vs конфликт, используя binding
Создал 2 приложения: 1ое(Основное) - в котором есть нижнее меню из 3-х элементов. Каждый отдельный элемент меню - фрагмент, на котором отображает отличная от другого информация. Во 2ом приложении(созданный фрагмент) - то что будет отображаться на отдельном фрагменте из меню(показалось что проще сделать каждый фрагмент отдельно, протестировать его, а потом добавить в основное приложение). Возникла проблема переноса созданного фрагмента в основную часть. Добавленный элемент отображается правильно, но кнопки не функционируют(начиная с кнопки Add, добавляющей View, заканчивая последней). Насколько понял, проблема в отображаемом layout в MainActivity.kt, используя binding, но не могу понять как решить это.
Структура проекта.
MainActivity.kt
package com.example.sapr_2
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.example.sapr_2.Classes.Rod
import com.example.sapr_2.databinding.ActivityMainBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.example.sapr_2.databinding.FragmentPreprocessorBinding // фрагмент на котором добавляются стержни
class MainActivity : AppCompatActivity() {
private var _bindingPreprocessor: FragmentPreprocessorBinding? = null // биндинг к 1 фрагменту меню
private val bindingPreprocessor get() = _bindingPreprocessor!!
private var _bindingActivityMain: ActivityMainBinding? = null
private val bindingActivityMain get() = _bindingActivityMain!!
private var rodsList = ArrayList<Rod>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_bindingPreprocessor = FragmentPreprocessorBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
val navController = findNavController(R.id.container_fragment)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
bottomNavigationView.setupWithNavController(navController)
//setContentView(bindingPreprocessor.root)
bindingPreprocessor.buttonAdd.setOnClickListener {
addNewView()
}
bindingPreprocessor.buttonRemove.setOnClickListener {
removeLastView()
}
bindingPreprocessor.buttonSubmitList.setOnClickListener {
saveData()
}
bindingPreprocessor.buttonShowList.setOnClickListener {
showData() //вывод введённых данных через Toast.makeText()
}
Log.d("SaprLog", "OnCreate")
}
private fun addNewView() {
val inflater = LayoutInflater.from(this).inflate(R.layout.row_add_rod, null)
bindingPreprocessor.parentLinearLayout.addView(inflater, bindingPreprocessor.parentLinearLayout.childCount)
}
private fun removeLastView() {
val view = bindingPreprocessor.parentLinearLayout.getChildAt(bindingPreprocessor.parentLinearLayout.childCount-1)
bindingPreprocessor.parentLinearLayout.removeView(view)
}
private fun saveData() {
rodsList.clear()
val count = bindingPreprocessor.parentLinearLayout.childCount // он считает кол-во элементов в контейнере
var v: View?
for (i in 0 until count) {
v = bindingPreprocessor.parentLinearLayout.getChildAt(i)
val rodLength: EditText? = v.findViewById(R.id.length_rod)
val rodb: EditText? = v.findViewById(R.id.b_rod)
val rodE: EditText? = v.findViewById(R.id.E_rod)
val rodSigma: EditText? = v.findViewById(R.id.Sigma_rod)
val rod= Rod()
rod.L = rodLength?.text.toString().toInt() //--добавление 1 переменной L
rod.b = rodb?.text.toString().toDouble() //--добавление 2 переменной b
rod.E = rodE?.text.toString().toDouble() //--добавление 3 переменной Е
rod.Sigma = rodSigma?.text.toString().toDouble() //--добавление 4 переменной Sigma
rodsList.add(rod)
}
}
Я добавил реализацию функций addNewView(), removeLastView() и saveData(), чтобы показать, что они работают, получая данные из Layout fragment_preprocessor.xml от bindingPreprocessor
Если раскомментировать строку //setContentView(bindingPreprocessor.root), то выведется рабочий Layout(кнопки функционируют), но без нижнего меню, то есть сменить фрагмент невозможно
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/navigation"
app:defaultNavHost="true"
android:id="@+id/container_fragment"
android:layout_above="@id/bottom_navigation_view"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/menu"
android:layout_alignParentBottom="true"
android:id="@+id/bottom_navigation_view"
app:labelVisibilityMode="selected" />
</RelativeLayout>
fragment_preprocessor.xml
<LinearLayout
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"
android:orientation="vertical"
tools:context=".fragments.Preprocessor">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:text="@string/rods_input"
android:textColor="@color/white"
android:textSize="15sp"
android:layout_gravity="center"/>
<LinearLayout
android:id="@+id/parent_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<Button
android:id="@+id/button_add"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
android:drawableEnd="@drawable/ic_baseline_add_24"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/add"
android:textAllCaps="false"
android:textColor="@color/white"/>
<Button
android:id="@+id/button_remove"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginStart="15dp"
android:layout_marginTop="1dp"
android:drawableEnd="@drawable/ic_baseline_remove_24"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/remove"
android:textAllCaps="false"
android:textColor="@color/white"/>
<Button
android:id="@+id/button_submit_list"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="1dp"
android:layout_marginRight="15dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/submit_list"
android:textAllCaps="false"
android:textColor="@color/white" />
<Button
android:id="@+id/button_show_list"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="1dp"
android:layout_marginRight="15dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/show_list_data"
android:textAllCaps="false"
android:textColor="@color/white" />
</LinearLayout>
navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/navigation"
app:startDestination="@id/preprocessor">
<fragment
android:id="@+id/postprocessor"
android:name="com.example.sapr_2.fragments.Postprocessor"
android:label="fragment_postprocessor"
tools:layout="@layout/fragment_postprocessor" />
<fragment
android:id="@+id/processor"
android:name="com.example.sapr_2.fragments.Processor"
android:label="fragment_processor"
tools:layout="@layout/fragment_processor" />
<fragment
android:id="@+id/preprocessor"
android:name="com.example.sapr_2.fragments.Preprocessor"
android:label="fragment_preprocessor"
tools:layout="@layout/fragment_preprocessor" />
</navigation>




