SlumpA
SlumpA

Reputation: 892

HowTo prevent Views from changing during rotation

I've written a simple application which has a TextView which, when clicked, changes into an EditText.

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Main extends Activity {
    static Context context;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        LinearLayout lL = new LinearLayout(this);
        TextView tv1 = new TextView(this);
        tv1.setText("tv1");
        tv1.setClickable(true);
        lL.addView(tv1);
        setContentView(lL);
        tv1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LinearLayout parent = (LinearLayout) v.getParent();
                parent.removeAllViews();
                EditText eT = new EditText(context);
                eT.setHint("Enter text here");
                parent.addView(eT, -1, -2);
                eT.requestFocus();
            }
        });
    }
}

But, when I rotate my phone, the text I've entered disappears, and the View returns to the TextView.

I know that when I rotate my phone, the activity pauses, stops, is destroyed, to be recreated, restarted, resumed again. But how can I keep my EditView with it's text, focus...?

I know this is a noobish question, as I've most likely missed something from the activity lifecycle guide from developer.android.com

Upvotes: 0

Views: 506

Answers (2)

Saugat man ligal
Saugat man ligal

Reputation: 21

You can modify in manifest file.This will help to not change orientation.I think will solve your problem

<activity
            android:name="com.example.bizzapp.StitchdMain"
            android:alwaysRetainTaskState="true"
            android:keepScreenOn="true"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

//HOPE IT HELPS

Upvotes: 0

Booger
Booger

Reputation: 18725

The basic concept, is that you need to capture and save the current state of your app during the life-cycle event that occurs right before the Activity is destroyed, then apply that saved state to your newly created Activity after it has been recreated after rotation

Here is one (of many) good SO questions addressing this: Android: Efficient Screen Rotation Handling

Upvotes: 1

Related Questions