I am trying to to create a Spinner inside a Fragment but I am getting error in the ArrayAdapter constructor call. I don't know why, but it has a red underline. Other than that, there is no error. When I'm using the same ArrayAdapter in an Activity it works, but in a Fragment, it gives an error.
My FirstFragment.kt:
class FirstFragment : Fragment() {
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
/*Find the id of spinner*/
val spinner = lol
/*set an adapter with strings array*/
spinner.adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, resources.getStringArray(R.array.atoms)) as SpinnerAdapter?
/*set click listener*/
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
/*Do something if nothing selected*/
}
}
button.setOnClickListener {
if (
editText2.text.toString().length > 0 &&
editText.text.toString().length > 0) {
val num2 = editText.text.toString().toDouble()
val num1 = editText2.text.toString().toDouble()
val num = num1/num2
textView.setText("$num moles")
}
else {
textView.setText("Please Enter a correct value")
}
}
}
}
My fragment_first.xml:
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.a3.aakap.ftrial.FirstFragment">
<android.support.constraint.ConstraintLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="294dp"
android:layout_height="80dp"
android:layout_weight="1"
android:text="Amswer : No of Moles"
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="right|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.556" />
<TextView
android:id="#+id/textView1"
android:layout_width="143dp"
android:layout_height="46dp"
android:layout_weight="1"
android:text="Amount in Grams "
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="left|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.066"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.305" />
<Spinner
android:id="#+id/lol"
android:layout_width="145dp"
android:layout_height="57dp"
app:layout_anchorGravity="left|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
<Button
android:id="#+id/button"
android:layout_width="138dp"
android:layout_height="43dp"
android:text="Calculate"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.788" />
<EditText
android:id="#+id/editText"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="bottom|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.762"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
<EditText
android:id="#+id/editText2"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="center_horizontal|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.716"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.288" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
The problem is in this constructor call:
spinner.adapter = ArrayAdapter(
this,
R.layout.support_simple_spinner_dropdown_item,
resources.getStringArray(R.array.atoms)
) as SpinnerAdapter
The argument this must be a reference to a Context, and a Fragment is not a Context. In an Activity it works because an Activity is a Context.
The solution is to replace this with activity:
spinner.adapter = ArrayAdapter(
activity,
R.layout.support_simple_spinner_dropdown_item,
resources.getStringArray(R.array.atoms)
)
i came here looking for some answers but i found my solution better and shorter i guess and complete the mission i'll just drop it here in case
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getCates()
}
the function
private fun getCates() {
val categories = MyApplication().getCategories()
val adapter = ArrayAdapter(requireContext(), R.layout.list_item, categories)
(binding.autocomplete as? AutoCompleteTextView)?.setAdapter(adapter)
binding.autocomplete.setOnItemClickListener { _, _, i, _ ->
category = categories[i]
Log.d(TAG,"$category")
}
}
PS : i get the list items from firebase you can add items lovaly
Related
Spinner doesn't display items. I'm making program for inventorization now. I get data from API. And I have the problem. Spinner doesn't show items. I add items to ArrayList and then add this list to spinner adapter. I've tried a lot of thing that i found at stackoverflow and another sites. But nothing helps me.
Code:
activity_add_classes.xml:
<pre><code>
<TextView
android:id="#+id/add_class_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Добавить кабинет"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="25dp"
/>
<EditText
android:id="#+id/class_number_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/add_class_label"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="16dp"
android:hint="Номер класса"
android:textSize="20sp"
android:singleLine="true"
android:maxLength="3"
android:digits="1234567890"
/>
<Spinner
android:id="#+id/corps_spinner"
app:layout_constraintTop_toBottomOf="#id/class_number_add"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/corps"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
/>
<Spinner
android:id="#+id/inventories_spinner"
android:layout_width="match_parent"
android:layout_height="75dp"
app:layout_constraintTop_toBottomOf="#id/corps_spinner"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
android:spinnerMode="dropdown"
app:layout_constraintEnd_toEndOf="parent"
/>
<EditText
android:id="#+id/count_of_inventory"
android:layout_width="100dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/inventories_spinner"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
android:maxLength="2"
android:digits="1234567890"
android:singleLine="true"
/>
<Button
android:id="#+id/add_inventory_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Добавить"
app:layout_constraintTop_toBottomOf="#id/inventories_spinner"
android:layout_margin="16dp"
app:layout_constraintEnd_toEndOf="parent"
/>
AddClassesActivity.kt:
enter code here
package com.example.inventorizationmpt
class AddClassesActivity : AppCompatActivity() {
lateinit var inventoriesSpinner: Spinner
lateinit var listInventory : ArrayList
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_classes)
listInventory = ArrayList()
inventoriesSpinner = findViewById(R.id.inventories_spinner)
getInventories()
spinAdapt()
}
fun spinAdapt(){
val spinnerAdapter = ArrayAdapter(this#AddClassesActivity, android.R.layout.simple_spinner_item,listInventory)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerAdapter.notifyDataSetChanged()
inventoriesSpinner.adapter = spinnerAdapter
}
fun getInventories(){
val inventorizationService = ServiceBuilder.buildService(InventorizationService::class.java)
val requestCall = inventorizationService.getInventoriesList()
requestCall.enqueue(object : Callback>{
override fun onResponse(
call: Call>,
response: Response>
) {
if (response.isSuccessful){
val listForSpinner = response!!.body()
for (i in 0..listForSpinner!!.size - 1){
listInventory.add(
ItemOfInventory(
listForSpinner[i].id_Inventory,
listForSpinner[i].inventory_Name
)
)
}
}else {
Toast.makeText(this#AddClassesActivity, "Что-то пошло не так. Ошибка со стороны сервера", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call>, t: Throwable) {
Toast.makeText(this#AddClassesActivity, "Что-то пошло не так. Ошибка со стороны сервера", Toast.LENGTH_LONG).show()
}
})
}
}
I have an activity and its layout, I am accessing xml field using ActivityQuotesBinding, activity_quotes.xml has no databinding information.
How did the ActivityQuotesBinding got created.
can some one share some light on this please
I want to do something similar for a fragment but no idea how binding works in this bellow code
thanks in advance
R
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.quotes.QuotesActivity">
<TextView
android:id="#+id/textView_quotes"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.55"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:scrollbars="vertical"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
tools:text="I like pineapples. - Thomas Jefferson"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editText_quote"
android:layout_width="0dp"
app:layout_constraintWidth_percent="0.7"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:hint="Quote"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_quotes"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editText_author"
android:layout_width="0dp"
app:layout_constraintWidth_percent="0.7"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:hint="Author"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText_quote"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/button_add_quote"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:backgroundTint="?colorAccent"
android:text="Add Quote"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="#+id/editText_author"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/editText_quote"
app:layout_constraintTop_toTopOf="#+id/editText_quote"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintWidth_percent="0.25" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity
class QuotesActivity : AppCompatActivity() {
private lateinit var binding: ActivityQuotesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityQuotesBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
initializeUI()
}
private fun initializeUI() {
val factory = InjectorUtils.provideQuotesViewModelFactory()
val viewModel = ViewModelProviders.of(this, factory)
.get(QuotesViewModel::class.java)
viewModel.getQuotes().observe(this, Observer {quotes ->
val stringBuilder = StringBuilder()
quotes.forEach {quote ->
stringBuilder.append("$quote\n\n")
}
binding.textViewQuotes.text = stringBuilder.toString()
})
binding.buttonAddQuote.setOnClickListener {
val quote = Quote(binding.editTextQuote.text.toString(), binding.editTextAuthor.text.toString())
viewModel.addQuotes(quote)
binding.editTextQuote.setText("")
binding.editTextAuthor.setText("")
}
}
}
You are actually using viewbinding, which is totally different from databinding.
When you specify in your module to enable viewbinding, all your layouts will be mapped to a class that follows that name convention that you noticed "LayoutfilenameBinding".
android {
...
buildFeatures {
viewBinding true
}
}
So, to access a fragment layout using viewbinding, you have to do pretty much the same code with some variances.
Lets say that your fragment's layout is fragment_layout.xml
private var _binding: FragmentLayoutBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentLayoutBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
Source:
https://developer.android.com/topic/libraries/view-binding
In my app I'm using custom view containing a TextInputLayout with the following code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/input_layout"
style="#style/UbiInput2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="-"
android:orientation="horizontal"
app:boxBackgroundColor="#color/white">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/input_value"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPersonName" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.appcompat.widget.LinearLayoutCompat>
And the kotlin
class TextInputView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
var errorMessage: String? = ""
init {
inflate(context, R.layout.text_input_view, this)
val attributes = context.obtainStyledAttributes(attrs, R.styleable.TextInputView)
val inputLayout = findViewById<TextInputLayout>(R.id.input_layout)
val inputValue = findViewById<TextInputEditText>(R.id.input_value)
inputLayout.hint = attributes.getString(R.styleable.TextInputView_hint)
inputValue.hint = attributes.getString(R.styleable.TextInputView_placeholderText)
inputLayout.isExpandedHintEnabled =
attributes.getBoolean(R.styleable.TextInputView_expandedHintEnabled, true)
errorMessage = attributes.getString(R.styleable.TextInputView_errorMessage)
inputLayout.isHelperTextEnabled = false
inputValue.inputType =
attributes.getInt(
R.styleable.TextInputView_android_inputType,
InputType.TYPE_CLASS_TEXT
)
if (attributes.hasValue(R.styleable.TextInputView_android_maxLength)) {
inputValue.filters += InputFilter.LengthFilter(
attributes.getInt(
R.styleable.TextInputView_android_maxLength,
100
)
)
}
inputValue.gravity =
attributes.getInt(R.styleable.TextInputView_android_gravity, Gravity.START)
if (attributes.getBoolean(R.styleable.TextInputView_android_gravity, false)) {
inputLayout.helperText = attributes.getString(R.styleable.TextInputView_helperText)
}
if (attributes.getBoolean(R.styleable.TextInputView_helperTextEnabled, false)) {
inputLayout.isHelperTextEnabled = true
inputLayout.helperText = attributes.getString(R.styleable.TextInputView_helperText)
}
inputLayout.startIconDrawable =
attributes.getDrawable(R.styleable.TextInputView_startIconDrawable)
attributes.recycle()
}
}
#BindingAdapter("textValue")
fun TextInputView.setTextValue(value: String?) {
value?.let {
setValue(value)
}
}
#InverseBindingAdapter(attribute = "textValue")
fun TextInputView.getTextValue(): String {
return value()
}
#BindingAdapter("textValueAttrChanged")
fun TextInputView.setListener(textAttrChanged: InverseBindingListener) {
val inputValue = findViewById<TextInputEditText>(R.id.input_value)
inputValue.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
textAttrChanged.onChange()
}
})
}
I have the following screen which go to the next fragment on button click. Using Navigation component.
But from the next screen, when I'm pressing back button to come back to the search form, the TextInputLayout values for hint, and helperText are all the same.
The only place I set those is inside the custom view. And from debugging I can see that all the correct values are set at that time.
I'm a bit out of ideas about what's going on there. Any hints would be appreciated.
Material library version used: 1.3.0-alpha04
All codebase has been migrated to view binding according the latest changes
The View is used as followed:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.ubigo.features.v2.products.taxi.SearchViewModel" />
<variable
name="dateFormat"
type="com.ubigo.ubicore.date.UbiDate" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/rental_search_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/background">
<androidx.cardview.widget.CardView
android:id="#+id/rental_search_form"
style="#style/WhiteCardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView10">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.ubigo.ubicore.ui.TextInputView
android:id="#+id/pickup"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:hint="#string/product_start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:startIconDrawable="#drawable/ic_calendar"
app:textValue="#{dateFormat.getPrettyDate(viewModel.pickupDateTime)}" />
<View
android:id="#+id/divider6"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="?android:attr/listDivider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pickup" />
<com.ubigo.ubicore.ui.TextInputView
android:id="#+id/dropoff"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:hint="#string/product_end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/divider6"
app:startIconDrawable="#drawable/ic_calendar"
app:textValue="#{dateFormat.getPrettyDate(viewModel.destinationDatetime)}" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<com.ubigo.ubicore.ui.LoaderButton
android:id="#+id/rental_search_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:text="#string/product_rental_show_car"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rental_search_location" />
<androidx.cardview.widget.CardView
android:id="#+id/rental_search_location"
style="#style/WhiteCardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rental_search_form">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.ubigo.ubicore.ui.TextInputView
android:id="#+id/user_location"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:helperText="#string/product_rental_location"
app:helperTextEnabled="true"
app:hint="#string/product_pickup_location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:startIconDrawable="#drawable/ic_location_on_black_24dp"
app:textValue="#{viewModel.depAddress}" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/textView10"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="#string/product_rental_weekend"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
And the initialization of the Fragment:
class RentalSearchFragment : Fragment() {
val viewModel: SearchViewModel by viewModel()
private val binding get() = _binding!!
private var _binding: FragmentRentalSearchBinding? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
if (_binding == null) {
_binding = FragmentRentalSearchBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
binding.dateFormat = UbiDate()
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
I was able to solve this exact problem by implementing onSaveInstanceState, onRestoreInstanceState, dispatchSaveInstanceState, dispatchRestoreInstanceState, and setValues as described here
http://www.devexchanges.info/2016/03/custom-compound-view-in-android.html
The linked above goes into all the necessary detail about how to implement these functions. There's also undoubtedly countless other sources you can find about how to implement this android paradigm.
I faced a strange problem : I can't add more than one object dynamically on a LinearLayout , if they were already things , that works, So That can display multiple views
I tried with different views , there is only problems when i try to push one after the other
(there is two buttons in index 0 and 1 to test for multiple objects on the layout)
CODE :
val view = layoutInflater.inflate(R.layout.sensor_item, container, false)
val view2 = layoutInflater.inflate(R.layout.nosensor_item, container, false)
val insertPoint = viewOfLayout.findViewById(R.id.box_Parent) as LinearLayout
insertPoint.addView(view, 2)
//insertPoint.addView(view2, 3) //works
This Works too :
//insertPoint.addView(view, 3)
insertPoint.addView(view2, 2) //works
This doesn't works :
insertPoint.addView(view, 2)
insertPoint.addView(view2, 3) //doesn't works
Full Code (fragments.kt):
package com.corrupted.radheat.TEMPER
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import kotlinx.android.synthetic.main.sensor_item.view.*
class EditFragment : Fragment() {
lateinit var option : Spinner
lateinit var result : TextView
private lateinit var viewOfLayout: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewOfLayout = inflater.inflate(R.layout.edit_fragment, container, false)
//create a view to inflate the layout_item (the xml with the textView created before)
val view = layoutInflater.inflate(R.layout.sensor_item, container, false)
val view2 = layoutInflater.inflate(R.layout.nosensor_item, container, false)
val insertPoint = viewOfLayout.findViewById(R.id.box_Parent) as LinearLayout
insertPoint.addView(view, 2)
insertPoint.addView(view2, 3)
option = view.spinner as Spinner
result = view.textView7 as TextView
val options = arrayOf("A","V")
option.adapter = ArrayAdapter<String>(activity,android.R.layout.simple_list_item_1,options)
option.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
result.text = "0"
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
result.text = options[position]
}
}
return viewOfLayout
}
class InfoFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.info_fragment, container, false)
}
}
class ParamsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.parameters_fragment, container, false)
}
}
Code of 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:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/box_Parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Code of the added view :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:fillViewport="true"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="12dp"
android:background="#color/background_Item_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:text=".0 C°"
android:textColor="#color/Text_Color_Light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/textView8"
app:layout_constraintStart_toEndOf="#+id/textView8"
app:layout_constraintTop_toTopOf="#+id/textView8"
app:layout_constraintVertical_bias="0.625" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_marginStart="4dp"
android:text=".0 C°"
android:textColor="#color/Text_Color_Light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/textView5"
app:layout_constraintStart_toEndOf="#+id/textView5"
app:layout_constraintTop_toTopOf="#+id/textView5"
app:layout_constraintVertical_bias="0.79" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="00"
android:textColor="#color/Text_Color_Light"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageButton"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.937" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:text="#string/ROOMtext"
android:textColor="#color/Text_Color_Light"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="#+id/spinner"
android:layout_width="45dp"
android:layout_height="43dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="8dp"
android:background="#color/UI_ITEM_OVERLAP_LIGHT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="40dp"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_keyboard_arrow_up_black_24dp" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="40dp"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="6dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageButton"
app:srcCompat="#drawable/ic_keyboard_arrow_down_black_24dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="00"
android:textColor="#color/Text_Color_Light"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.652" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.kt :
package com.corrupted.radheat.TEMPER
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.widget.*
class MainActivity : AppCompatActivity() {
private val fragmentManager = supportFragmentManager
private val fragmentTransaction = fragmentManager.beginTransaction()
private val editfragment = EditFragment()
private val infofragment = InfoFragment()
private val parametersfragment = ParamsFragment()
private fun showFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.action_edit -> {
showFragment(editfragment)
return#OnNavigationItemSelectedListener true
}
R.id.action_info-> {
showFragment(infofragment)
return#OnNavigationItemSelectedListener true
}
R.id.action_Settings-> {
showFragment(parametersfragment)
return#OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fragmentTransaction.add(R.id.fragment_container, infofragment)
fragmentTransaction.commit()
setContentView(R.layout.activity_main)
val navigation = findViewById<BottomNavigationView>(R.id.activity_main_bottom_navigation)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
}
}
Pic of it working : https://imgur.com/gallery/mLb4G5b
Thanks
Hello everyone in my fragment, i have added a spinner in my fragment and little bit of code to calculate moles but when i rotate screen it crashes and throw an error by i don't know why it crashes , When try to check for Non-null object i don't What that is the cause of error , Here is the error :
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull
Here is my first fragment file :
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
/*Find the id of spinner*/
val spinner = lol
/*set an adapter with strings array*/
spinner.adapter = ArrayAdapter(activity, R.layout.support_simple_spinner_dropdown_item, resources.getStringArray(R.array.atoms)) as SpinnerAdapter
/*set click listener*/
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
/*Do something if nothing selected*/
}
}
button.setOnClickListener {
if (
editText2.text.toString().length > 0 &&
editText.text.toString().length > 0) {
val num2 = editText.text.toString().toDouble()
val num1 = editText2.text.toString().toDouble()
val num = num1/num2
textView.setText("$num moles")
}
else {
textView.setText("Please Enter a correct value")
}
}
}
Here is my fragment_first.xml file :
<android.support.constraint.ConstraintLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="294dp"
android:layout_height="80dp"
android:layout_weight="1"
android:text="Amswer : No of Moles"
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="right|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.556" />
<TextView
android:id="#+id/textView1"
android:layout_width="143dp"
android:layout_height="46dp"
android:layout_weight="1"
android:text="Amount in Grams "
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="left|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.066"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.305" />
<Spinner
android:id="#+id/lol"
android:layout_width="145dp"
android:layout_height="57dp"
app:layout_anchorGravity="left|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
<Button
android:id="#+id/button"
android:layout_width="138dp"
android:layout_height="43dp"
android:text="Calculate"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.788" />
<EditText
android:id="#+id/editText"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="bottom|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.762"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
<EditText
android:id="#+id/editText2"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="center_horizontal|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.716"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.288" />
</android.support.constraint.ConstraintLayout>
Add ? in
view = View?
Here is code
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
It is correct, annotating the "view" parameter as nullable does appear to correct the issue.
It appears that the Kotlin generated code is incorrect as the auto-generated code marks "view" without the nullable attribute.