I am currently working on a line entry calculator application for android. When the Button "button" is clicked it should add two textviews into the linearlayout "holder_mai开发者_如何转开发n_layout" which is within a scrollview. One of the textviews is the text value of an edit text to the left, the other is the evaluated answer to the right. All of this works, but when I reorient the phone (from vertical to landscape or landscape to a different landscape) the linear layout is blank again. I know its not smart to leave all of those textviews without a way to access them but this is proof of concept at the moment.
Why is the scrollview empty when I rotate the phone. And how can i prevent this from happening.
public class main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout holder_main_layout=(LinearLayout)findViewById(R.id.linearLayout2);
final CalculatorBase calc=new CalculatorBase();
final Button button = (Button) findViewById(R.id.button1);
final ScrollView scroller=(ScrollView)findViewById(R.id.scrollView1);
final main self=this;
final EditText input_text=(EditText)findViewById(R.id.editText1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView input_view=new TextView(self);
input_view.setText(input_text.getText());
holder_main_layout.addView(input_view);
TextView output_view=new TextView(self);
output_view.setText(String.valueOf(calc.eval_expression(input_text.getText().toString())));
output_view.setGravity(5);
holder_main_layout.addView(output_view);
input_text.setText("");
scroller.fullScroll(ScrollView.FOCUS_UP);
}
});
}
}
By default Android destroys and re-create Activity when orientation changes. You can do two things:
- save state as described here: https://developer.android.com/reference/android/app/Activity.html#SavingPersistentState
- handle screen orientation change yourself: https://developer.android.com/guide/topics/resources/runtime-changes.html
Try the second method first. Modify your manifest to include android:configChanges
line in Activity definition:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
Then place following method in Activity code:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
精彩评论