I have looked at other posts and tried out the solutions suggested but none have worked for me. I have a simple app, that has a button and Textview and when the user presses the button the value in TextView will increase by 1. (The textview only has numbers).
I have different layout for my portrait and landscape mode and I was able to freeze the value on screen orientation by using this code in my XML android:freezesText="true"
. However, the problem that I am having now is that on screen orientation when the user presses the button to increament the value of TextView by 1, the value in textview starts from 0. For example
For example on portrait mode the value is 23, when the user rotates the screen to landscape and presses the button the value will go back to 1. How do I make the value start from 23.
Below is my code;
Portrait layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/textview"/>
<Button
android:id="@+id/up"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/up" />
</LinearLayout>
Landspace layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/textview"/>
<Button
android:id="@+id/up"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/up" />
</LinearLayout>
Java code
int counter = 0;
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView)findViewById(R.id.textview );
final Button up = (Button)findViewById(R.id.up);
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
textview.setText("" + counter);
}
});
}
may be you somehow reload the activity parameters when going from portrait to landscape, which will accordingly resets counter
value to 0
again when rotating. you may try to make it static
variable to avoid conflicting.
private static int counter = 0;