从PORTRAIT更改为横向和横向更改为纵向时取消EditText的内容

时间:2013-11-28 18:51:59

标签: android android-layout android-edittext android-orientation

在我的应用程序中,使用以下代码在java中创建布局:

frameLayout = new FrameLayout(this);
frameLayout.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

HorizontalScrollView HSC = new HorizontalScrollView(this);
HSC.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));
frameLayout.setBackgroundResource(R.drawable.lavagna1);       
ScrollView VSC = new ScrollView(this);
VSC.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TableLayout tableLayout = new TableLayout(this);
tableLayout.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  

inflater = (LayoutInflater) SecondaAttivitaEQ.this.getSystemService(LAYOUT_INFLATER_SERVICE);

layout = inflater.inflate(R.layout.keyboardmatrix,(ViewGroup) findViewById(R.id.ciao));

    for ( int i = 0; i < grado; i++) {
        tableRow = new TableRow(this); 
        tableRow.setGravity(Gravity.CENTER);

        for (int j = 0; j < 1; j++) {

            valore[i][j].setHint(" c" + i + " ");
            valore[i][j].setPadding(10, 10, 10, 10);
            tableRow.addView(valore[i][j]);
            tableLayout.addView(tableRow);

        }
     }

    VSC.addView(tableLayout);
    HSC.addView(VSC);
    frameLayout.addView(HSC);
    setContentView(frameLayout);

    secondo = new Button (this);
    secondo.setText("SOLVE");
    secondo.setTextColor(0xffffffff);
    secondo.setBackgroundResource(R.drawable.but_ok);
    tableLayout.addView(secondo);

此代码创建一个EditText表,问题在于屏幕的旋转,实际上如果我在EditText中输入值并且手机被旋转,应用程序会通过删除所有内容来重新创建布局。 EditText。 你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

每次定向改变,android创建新视图并销毁旧视图。您可以在方向更改时保存数据,并在创建新视图时重新初始化

使用onConfigurationChanged活动方法检测方向更改

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
  }

像这样更新AndroidManifest.XML以包含android:configChanges

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">