Don't run function on onRestoreInstanceState - android

I am working on an app that when you go to a screen you select your location from a dialog which is created within onCreate. Once the location is selected it writes it into a predined TextView. A problem that I am having is when the screen orientation changes it recreates the dialog and I'm trying to have it not fire the dialog function.
Here is the basics of what I have within the class file.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emergpolice);
form_location = (TextView) findViewById(R.id.input_location);
if(form_location == null || form_location.getText().equals("")){
setLocation();
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("LOCATION", (String)form_location.getText());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
form_location.setText(savedInstanceState.getString("LOCATION"));
}
public void setLocation(){
db = new DatabaseHandler(this);
db.open();
final CharSequence[] locOpt = {getString(R.string.dialog_items_current_location),getString(R.string.dialog_items_home),getString(R.string.dialog_items_enter_manually)};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.header_choose_location));
builder.setSingleChoiceItems(locOpt, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
if(locOpt[item].equals(getString(R.string.dialog_items_home))){
Cursor cur = db.userInfo();
String address = cur.getString(cur.getColumnIndex("address"));
String city = cur.getString(7);
String county = cur.getString(8);
String state = cur.getString(9);
String zip = cur.getString(10);
db.close();
form_location.setText(address + ", " + city + ", " + county + ", " + state + ", " + zip);
}
if(locOpt[item].equals(getString(R.string.dialog_items_current_location))){
Toast.makeText(getApplicationContext(), locOpt[item], Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
And the TextView in my layout is
<TextView
android:id="#+id/input_location"
android:layout_width="wrap_content"
android:layout_below="#+id/text_location"
android:layout_height="wrap_content"
android:text="" />
As far as firing setLocation() is have tried several scenarios to check the string length, whether null or not. When the screen changes it shows the original chosen location, but still fires the dialog.

You always call the method setLocation because each time the onCreate method of the Activity is called form_location.getText().equals("") will be true(because the TextView is recreated(and most likely you don't set text on it in the layout file)).
To avoid this, use the savedInstanceState of the onCreate method:
if (savedInstanceState == null){
// if savedInstanceState is null the activity is created for the first time
setLocation();
} else {
// if not null then the activity is recreated so restore the TextView text
form_location.setText(savedInstanceState.getString("LOCATION"));
}

You can set in the manifest file in the activity tag an attributed of configchange. If you set. The flag orientation than your activity will not be destroyed on every orientation change. So onceate will only be called once.

Related

How can I use savedInstanceState and show text in editText?

I want to save text in a editText and when I rotate the cell phone then it's showed again.
but, "it's showed again" this part doesn't work but, Toast is working.
I thought "setText" is the one...
here is the
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
name = editText.getText().toString();
showToast("saved : " + name);
}
});
if (savedInstanceState != null){
name = savedInstanceState.getString("name");
showToast("restore : " + name);
editText.setText("name");
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString("name", name);
super.onSaveInstanceState(outState);
}
public void showToast(String data){
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
}
You have wrapped the variable name in "" so you're inputting the actual text name as a string into the edit text, rather than the contents of that variable. Remove the quotation marks like so:
if (savedInstanceState != null) {
String text = savedInstanceState.getString("name");
editText.setText(text);
}
EDIT
I would also suggest that you capture the value of the text inside the edit text at the time of saveInstanceState(), incase the global 'name' variable happens to be null. Like so:
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
String text = editText.getText().toString();
outState.putString("name", text);
}

Count Down Timer app has issue when I change orientation

The layout of my app contains a TextView and a toggle Button. When the toggle Button is turned ON an AlertDialog appears and the user is prompted to give the time for the countdown to start. It works fine if I dont change the orientation while it counts down. However when I change orientation while the countdown keeps running the Dialog Box reappears which shouldn't. I know that changing orientation destroys and recreates my activity so given the fact that toggle button was ON before the activty is destroyed when it is recreated it continuous to be ON as it should be. So my question is if there is a way for the AlertDialog not to appear after the orientation change.
I have tried adding the following but it didnt work
Declared as class variable
public static final String TOGGLE_BUTTON_STATE = "OFF";
Trying to set the toggle Button to true
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: created.............");
mTextTime = (TextView) findViewById(R.id.textView);
mToggleButton = (ToggleButton) findViewById(R.id.toggleButton);
if((savedInstanceState != null) && TOGGLE_BUTTON_STATE.equals("ON")) {
Log.d(TAG, "onCreate: created after changing orientation........");
mToggleButton.setChecked(true);
}
mToggleButton.setOnCheckedChangeListener(this);
saving the state before it is destroyed
#Override
public void onSaveInstanceState(Bundle outState) {
if(mToggleButton.isChecked()) {
Log.d(TAG, "onSaveInstanceState: toggleButton is checked...........****");
outState.putString(TOGGLE_BUTTON_STATE, "ON");
}else {
Log.d(TAG, "onSaveInstanceState: toggleButton is not checked...........*****");
outState.putString(TOGGLE_BUTTON_STATE, "OFF");
}
super.onSaveInstanceState(outState);
}
//Listener for the ToggleButton
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Toast.makeText(this, "ON", Toast.LENGTH_SHORT).show();
// TOGGLE_BUTTON_ON = true;
//getting the xml user_input to java
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.user_input, null);
//search inside the view for the text_input
mTextUserInput = (EditText) view.findViewById(R.id.text_input);
//We create the builder and we use it to add functionality to the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Enter The Time");
//We create the user_input that has only the editext widget that we gonna use to get the
//time from the user
builder.setView(view);
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.show();
} else {
// OFF selected and timer must stop
// TOGGLE_BUTTON_ON = false;
timer.stop();
}
}
ps The countdown timer keeps running properly even after orientation change
Your way of loading the previously stored state in onCreate is false. You are saving the state correctly (but i would prefer storing it as a boolean) - but you are not reading it correctly from the savedInstance.
The way i would do it:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("TOGGLE_BUTTON_STATE", mToggleButton.isChecked());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(savedInstanceState != null) {
mToggleButton.setChecked(savedInstanceState.getBoolean("TOGGLE_BUTTON_STATE"));
}
mToggleButton.setOnCheckedChangeListener(this);
...
}
You can dismiss the alert dialog when the activity is going to be destroyed.
For example:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
...
// Save the dialog in an instance variable
mDialog = builder.show();
}
#Override
public void onStop() {
if (mDialog != null) {
mDialog.dismiss();
}
super.onStop();
}

onClickListener not found after rotation in android

This is a stripped down version of what I want to do. I have some stuff occurring inside the clickListener and want it to continue after orientation change. I save the variable and in the "if(saveInstanceState != null) section I retrieve the variable "count" and try to start the tasks inside the onClick method. The variable is saved properly (although not printed because the setText method in inside onClick. Also, the Log returns "false", meaning that the performClick method executed but did not find the clickListener.
I think this is a scope of variable issue, but am otherwise stumped. Thanks for any help.
public class MainActivity extends Activity {
Button countButton;
int count = 0;
TextView countWidget;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countButton = (Button)findViewById(R.id.button);
countWidget = (TextView)findViewById(R.id.textView);
if (savedInstanceState != null){
count = savedInstanceState.getInt("count");
boolean found = countButton.performClick();
Log.d("Message ", "found listener = " + found);
}
countButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count ++;
countWidget.setText("count = " + count);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", count);
}
}
Because you are calling performClick() before the call to setOnClickListener, thus when onCreate is called with your Bundle, it cannot find the callback.
The previous call is fine because when the user taps on the button, it's already way past onCreate where the callback is defined.
One solution is to move the Bundle check after setOnClickListener
countButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count ++;
countWidget.setText("count = " + count);
}
});
if (savedInstanceState != null){
count = savedInstanceState.getInt("count");
boolean found = countButton.performClick();
Log.d("Message ", "found listener = " + found);
}
performClick works (without crashing, if that's what you were expecting when the log returns false) because Android will check if there's any click listener defined, if not then just return false.
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
You can also set the onClick function from the layout file of your activity like this:
<Button
android:id="#+id/countButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Count"
android:onClick="onCountClick"/>
Now, after adding this to your layout file, define the function onCountClick in your activity's java file like this:
public void onCountClick(View v)
{
//Do your tasks here
}
If you do this, you won't be needing the onClickListener any more.
Hope it helps.

How to add a pop up/Dialog box and pass information back to the class in Android

I am trying to create a pop-up dialog to allow the user of my android app to add a new field to a list on their main page.
I've done a bit of research and found the Dialog/alertDialog option, but i haven't been able to get it working correctly.
Here is my MainActivity class:
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
//final Dialog dialog = new Dialog(this); //!!! ERROR HERE !!! //
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Button AddNewStudent = (Button) findViewById(R.id.AddNew);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
//db.addStudentProfile(new StudentProfile("Shannon", "White"));
//db.addStudentProfile(new StudentProfile(1,"Shannon", "White", "WhitehousePS", "30", "21" ));
/*AddNewStudent.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Using an alertDialog to get the user to enter in a new Student
dialog.setContentView(R.layout.add_new_student);
dialog.setTitle("Add a new student");
final EditText firstName=(EditText)dialog.findViewById(R.id.firstName);
final EditText surname=(EditText)dialog.findViewById(R.id.surname);
final EditText school=(EditText)dialog.findViewById(R.id.school);
final EditText age=(EditText)dialog.findViewById(R.id.age);
Button save=(Button)dialog.findViewById(R.id.save);
Button btnCancel=(Button)dialog.findViewById(R.id.cancel);
dialog.show();
}
});*/
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<StudentProfile> contacts = db.getAllStudents();
for (StudentProfile studProf : contacts) {
String log = "Id: "+studProf.getID()+" , First name: " + studProf.getFirstName() + ", Surname: " + studProf.getSurname() + ", School: " + studProf.getSchool() +
", Reading Level: "+ studProf.getReadingLevel() + ", Age: " + studProf.getAge();
// Writing Contacts to log
Log.d("Name: ", log);
}
db.getAllStudents();
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
It's linked to a very simple xml page that just has editible text fields.
My application won't even open with this code - i have tracked the issue down to this line:
final Dialog dialog = new Dialog(this);
at the top of my program.
IS this the best way to go about making a pop up dialog?
Also, what is the easiest way to pass the information back to the class to be stored in a database?
Any help would be much appreciated, thanks! :)
You can create some private variables at the top of your class, and get the text from the editText and put it into those variables in the dialog's button click handler method (where you have the 'sign in the user' comment.)
Sometimes it's also easyer to crate a dialog themed activity.

How to retain EditText data on orientation change?

I have a Login screen which consists of 2 EditTexts for Username and Password. My requirement is that on orientation change , input data(if any) in EditText should remain as it is and a new layout should also be drawn. I have 2 layout xml files- one in layout folder and other in layout-land folder. I am trying to implement following 2 approaches but none of them is perfect:
(1) configChanges:keyboardHidden - In this approach, I don't provide "orientation" in configChanges in manifest file. So I call setContentView() method in both onCreate() and onConfigurationChanged() methods. It fulfills both my requirements. Layout is changed and input data in EditTexts also remains as it is. But it has a big problem :
When user clicks on Login button, a ProgressDialog shows until server-response is received. Now if user rotates the device while ProgressDialog is running, app crashes. It shows an Exception saying "View cannot be attached to Window." I have tried to handle it using onSaveInstanceState (which DOES get called on orientation change) but app still crashes.
(2) configChanges:orientation|keyboardHidden - In this approach, I provide "orientation" in manifest. So now I have 2 scenarios:
(a) If I call setContentView() method in both onCreate() and onConfigurationChanged(), Layout is changed accordingly but EditText data is lost.
(b) If I call setContentView() method in onCreate() , but not in onConfigurationChanged(), then EditText data is not lost but layout also not changes accordingly.
And in this approach, onSaveInstanceState() is not even called.
So I am in a really intimidating situation. Is there any solution to this problem? Please help. Thanx in advance.
By default, Edittext save their own instance when changing orientation.
Be sure that the 2 Edittexts have unique IDs and have the same IDs in both Layouts.
That way, their state should be saved and you can let Android handle the orientation change.
If you are using a fragment, be sure it has a unique ID also and you dont recreate it when recreating the Activity.
A better approach is to let android handle the orientation change. Android will automatically fetch the layout from the correct folder and display it on the screen. All you need to do is to save the input values of the edit texts in the onSaveInsanceState() method and use these saved values to initialize the edit texts in the onCreate() method.
Here is how you can achieve this:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
...
...
String userName, password;
if(savedInstanceState!=null)
{
userName = savedInstanceState.getString("user_name");
password= savedInstanceState.getString("password");
}
if(userName != null)
userNameEdtTxt.setText(userName);
if(password != null)
passEdtTxt.setText(password);
}
>
#Override
protected void onSaveInstanceState (Bundle outState)
{
outState.putString("user_name", userNameEdtTxt.getText().toString());
outState.putString("password", passEdtTxt.getText().toString());
}
Give the element an id and Android will manage it for you.
android:id="#id/anything"
in onConfigurationChanged method, first get the data of both the edit texts in global variables and then call setContentView method. Now set the saved data again into the edit texts.
There are many ways to do this. The simplest is 2(b) in your question. Mention android:configChanges="orientation|keyboardHidden|screenSize" in your manifest so that Activity doesn't get destroyed on Orientation changes.
Call setContentView() in onConfigChange(). but before calling setContentView() get the EditText data into a string and set it back after calling setContentView()
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mEditTextData = mEditText.getText().tostring();//mEditTextData is a String
//member variable
setContentView(R.layout.myLayout);
initializeViews();
}
private void initializeViews(){
mEditText = (EditText)findViewById(R.id.edittext1);
mEdiText.setText(mEditTextData);
}
The following should work and is standard to the activities and fragments
#Override
public void onSaveInstanceState (Bundle outState)
{
outState.putString("editTextData1", editText1.getText().toString());
outState.putString("editTextData2", editText2.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate();
... find references to editText1, editText2
if (savedInstanceState != null)
{
editText1.setText(savedInstanceState.getString("editTextData1");
editText2.setText(savedInstanceState.getString("editTextData2");
}
}
Im restoring instance to restore values and it works fine for me :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask2);
if(savedInstanceState!=null)
onRestoreInstanceState(savedInstanceState);
}
Remove android:configChanges attribute from the menifest file and let android handle the orientation change your data in edittext will automatically remain.
Now The problem you mentioned is with the progress dialog force close this is because when the orientation is changed the thread running in backgroud is trying to update the older dialog component whihc was visible. You can handle it by closing the dialog on savedinstancestate method and recalling the proceess you want to perform onRestoreInstanceState method.
Below is a sample hope it helps solving your problem:-
public class MyActivity extends Activity {
private static final String TAG = "com.example.handledataorientationchange.MainActivity";
private static ProgressDialog progressDialog;
private static Thread thread;
private static boolean isTaskRunnig;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new EditText.OnClickListener() {
#Override
public void onClick(View v) {
perform();
isTaskRunnig = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void perform() {
Log.d(TAG, "perform");
progressDialog = android.app.ProgressDialog.show(this, null,
"Working, please wait...");
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
//isTaskRunnig = false;
}
});
thread = new Thread() {
public void run() {
Log.d(TAG, "run");
int result = 0;
try {
// Thread.sleep(5000);
for (int i = 0; i < 20000000; i++) {
}
result = 1;
isTaskRunnig = false;
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
Message msg = new Message();
msg.what = result;
handler.sendMessage(msg);
};
};
thread.start();
}
// handler to update the progress dialgo while the background task is in
// progress
private static Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "handleMessage");
int result = msg.what;
if (result == 1) {// if the task is completed successfully
Log.d(TAG, "Task complete");
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
isTaskRunnig = true;
}
}
}
};
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState" + isTaskRunnig);
if (isTaskRunnig) {
perform();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState");
if (thread.isAlive()) {
thread.interrupt();
Log.d(TAG, thread.isAlive() + "");
progressDialog.dismiss();
}
}
As pointed out by Yalla T it is important to not recreate the fragment. The EditText will not lose its content if the existing fragment is reused.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_frame);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
// Do not do this. It will recreate the fragment on orientation change!
// getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment_Places()).commit();
// Instead do this
String fragTag = "fragUniqueName";
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment) fm.findFragmentByTag(fragTag);
if (fragment == null)
fragment = new Fragment_XXX(); // Here your fragment
FragmentTransaction ft = fm.beginTransaction();
// ft.setCustomAnimations(R.xml.anim_slide_in_from_right, R.xml.anim_slide_out_left,
// R.xml.anim_slide_in_from_left, R.xml.anim_slide_out_right);
ft.replace(android.R.id.content, fragment, fragTag);
// ft.addToBackStack(null); // Depends on what you want to do with your back button
ft.commit();
}
Saving state = Saving (Fragment State + Activity State)
When it comes to saving the state of a Fragment during orientation change, I usually do this way.
1) Fragment State:
Save and Restore EditText value
// Saving State
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("USER_NAME", username.getText().toString());
outState.putString("PASSWORD", password.getText().toString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.user_name_fragment, parent, false);
username = (EditText) view.findViewById(R.id.username);
password = (EditText) view.findViewById(R.id.password);
// Retriving value
if (savedInstanceState != null) {
username.setText(savedInstanceState.getString("USER_NAME"));
password.setText(savedInstanceState.getString("PASSWORD"));
}
return view;
}
2) Activity State::
Create a new Instance when the activity launches for the first time
else find the old fragment using a TAG and the FragmentManager
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
fragmentManager = getSupportFragmentManager();
if(savedInstanceState==null) {
userFragment = UserNameFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.profile, userFragment, "TAG").commit();
}
else {
userFragment = fragmentManager.findFragmentByTag("TAG");
}
}
You can see the the full working code HERE
Below code is work for me. Need to care two things.
Each Input Field (Edit Text or TextInputEditText) assign unique id.
Manifest activity declaration should have on configuration change attribute with below values.
android:configChanges="orientation|keyboardHidden|screenSize"
Sample activity declaration in manifest.
<activity
android:name=".screens.register.RegisterActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:exported="true"
android:label="Registration"
android:theme="#style/AppTheme.NoActionBar" />
Sample declaration of
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/inputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:boxCornerRadiusBottomEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusBottomStart="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopStart="#dimen/boxCornerRadiusDP">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="#font/proxima_nova_semi_bold"
android:inputType="textCapWords"
android:lines="1"
android:textColor="#color/colorInputText"
android:textColorHint="#color/colorInputText" />
</com.google.android.material.textfield.TextInputLayout>
this may help you
if your android:targetSdkVersion="12" or less
android:configChanges="orientation|keyboardHidden">
if your android:targetSdkVersion="13" or more
android:configChanges="orientation|keyboardHidden|screenSize">

Categories

Resources