2013-07-29 1 views
5

버튼 클릭으로 레이아웃에 동적으로 추가 할 뷰를 만들었지 만 장치 가로를 회전하면 뷰가 사라집니다. 누군가 제 코드를보고 어떻게 이런 일이 일어나지 않게 할 수 있는지 설명해주십시오.안드로이드의 방향에 동적으로 추가 된 뷰가 사라짐

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

이 manifest.xml 태그에이 줄을 추가 TestContainerActivity 활동

android:ConfigChanges="keyboardHidden|orientation" 
3

에 다음 줄을 추가 : 여기

는 코드입니다.

android:configChanges="keyboardHidden|orientation|screenSize" 

이렇게하면 오리엔테이션 변경에 따른 활동을 피할 수 있습니다.

1

방향 변경을 방지하는 것보다 새로운 방향으로 레이아웃을 다시 만드는 것이 좋습니다.

귀하의 onCreate에서 (예 : 방향 변경의 결과로) 저장된 인스턴스가 있는지 확인하십시오.

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

당신은 (공유의 환경 설정 또는 onSavedInstanceState에서 중) 어떤 값을 유지해야합니다.

이 접근법은 방향을 잠그는 것보다 어렵지만 장기적으로는 더 나은 접근 방법이며 연구 노력에 충분히 가치가 있습니다.