2013-07-29 64 views
5

Tôi đã tạo chế độ xem được động theo bố cục từ một lần nhấp nút, nhưng khi tôi xoay ngang thiết bị, các chế độ xem sẽ biến mất. Ai đó có thể xem mã của tôi và giải thích cách ngăn điều này xảy ra.Lượt xem được thêm động sẽ biến mất theo hướng trong Android

Đây là mã:

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); 

} 

} 

Trả lời

-1

Thêm dòng sau vào TestContainerActivity hoạt động

android:ConfigChanges="keyboardHidden|orientation" 
3

Thêm dòng này trong manifest.xml Thẻ của bạn.

android:configChanges="keyboardHidden|orientation|screenSize" 

Điều này sẽ tránh hoạt động của bạn tái tạo khi thay đổi hướng.

1

Tốt hơn là cố gắng tạo lại bố cục theo hướng mới, thay vì chỉ ngăn thay đổi hướng.

Trong onCreate kiểm tra xem có trường hợp đã lưu (do thay đổi hướng) hay không, ví dụ:

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

Bạn có thể cần giữ lại một số giá trị (trong Shared Prefs hoặc onSavedInstanceState).

Cách tiếp cận này khó khăn hơn so với khóa định hướng, nhưng đó là một cách tiếp cận tốt hơn về lâu dài và cũng đáng để nỗ lực nghiên cứu.