Reset Content View in Android

620 Views Asked by At

I have dialog, which includes a spinner in a constraintLayout ("new_widget_layout.xml"). To get the id of the Spinner I use this code:

setContentView(R.layout.new_widget_layout)
val typeSpinner = findViewById<Spinner>(R.id.widgetTypeSpinner)
ArrayAdapter.createFromResource(this, R.array.types, android.R.layout.simple_spinner_item).also {
            it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            typeSpinner.adapter = it
        }
// The contentView is changed back, see below...

As you can see, I need to change the ContentView to my dialogLayout first, so I can get the id of the spinner. But if I want to change it back to the standard layout, my onclicklisteners don't work.

Example

val deleteButton = findViewById<Button>(R.id.deleteButton) // This is before the contentView is changed

deleteButton.setOnClickListener { // This is after the content View is changed back and forth and it does nothing
            // code
        }

I tried multiple things to change the contentView back to normal, like:

  • setContentView(findViewById<ConstraintLayout>(R.id.myLayout))
  • setContentView(R.layout.activity_main)

But nothing seems to work. All the buttons etc. show up correctly, but nothing happens, if they are clicked. It works, if I remove the code with the contentViews and the Spinner entirely.

1

There are 1 best solutions below

0
Kamal Nayan On

You can restart the activity and use a condition like

if(Common.layoutType ==1)
 setContentView(R.layout.activity_main)
else 
  setContentView(R.layout.your_layout)

and in onClickListener you can store a value in common class (if not one kindly make it)

Public class Common
   {
     Public static int layoutType = 1;
    }

and in onClickListener

Common.layoutType = YOUR_DESIRED_VALUE;
startActivity(); /// again start the same activity 

and when the activity will restart then during the check it will automatically set the desired layout accordingly.

Feel free to ask if something is unclear.