2013-07-29 10 views
5

ボタンをクリックしてレイアウトに動的に追加するビューを作成しましたが、デバイスのランドスケープを回転するとビューが消えます。誰かが私のコードを見て、これを止める方法を説明してもらえますか?ここでAndroidの向きで動的に追加されたビューが消える

はコードです:

public class TestContainerActivity extends Activity implements OnClickListener { 

LinearLayout containerLayout; 
Button testButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test_container); 

    testButton = (Button)findViewById(R.id.testContainerButton1); 
    testButton.setOnClickListener(this);   
    containerLayout = (LinearLayout)findViewById(R.id.testContainerLayout); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.test_container, menu); 
    return true; 
} 


@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    if(v==testButton){ 

     createNewLayout(); 

    } 
} 

public void createNewLayout(){ 

     LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View addView = layoutInflater.inflate(R.layout.container, null); 
     TextView textviewTest = (TextView)addView.findViewById(R.id.containerTextView4); 
     textviewTest.setText("TextView"); 

     containerLayout.addView(addView); 

} 

} 

答えて

-1

TestContainerActivity活動

android:ConfigChanges="keyboardHidden|orientation" 
3

に次の行を追加します。あなたのmanifest.xmlタグにこの行を追加します。

android:configChanges="keyboardHidden|orientation|screenSize" 

これは、オリエンテーションの変更であなたの活動が再作成されるのを防ぎます。

1

オリエンテーションの変更を防ぐのではなく、新しいオリエンテーションでレイアウトを再作成することをお勧めします。

あなたのonCreateでは、保存されたインスタンスが(向きの変更の結果として)存在するかどうかを確認します。

if (savedInstanceState == null) { 
     //create new button layout if previously clicked 
} 
else { 
     //normal start 
} 

いくつかの値(共有設定またはonSavedInstanceStateのいずれか)を保持する必要があります。

このアプローチは、方向をロックするよりも難しいですが、長期的にはより良いアプローチであり、研究努力の価値があります。

関連する問題