2014-03-06 103 views
0

我使用onConfigurationChanged方法來知道方向更改的時間。但是,當我調用其他佈局的按鈕不工作。更改佈局如果方向更改,按鈕錯誤

這裏是我的代碼:

IntroPage.java

package com.example.mysqltest; 

import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.widget.Button; 
import android.widget.Toast; 

public class IntroPage extends Activity implements OnClickListener { 

    private Button btnlogin; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.intropage); 


     btnlogin = (Button)findViewById(R.id.btnlogin); 

     btnlogin.setOnClickListener(this); 

    } 
    // Check screen orientation or screen rotate event here 
    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     setContentView(R.layout.intropage); 

     // Checks the orientation of the screen for landscape and portrait 
     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      setContentView(R.layout.intropage_landscape); 
      Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); 

     } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 
      Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); 

     } 
    } 




    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     Intent i = new Intent(IntroPage.this, Login.class); 
     startActivity(i); 


    } 



    } 

和我在清單XML寫android:configChanges="orientation|screenSize"。請有人幫助我...我可以做什麼與按鈕不工作?

+0

它應該是android:configChanges =「orientation | keyboardHidden」 –

+0

是的,但configChange工作正常,佈局更改,但按鈕不工作。 – user3386169

回答

0

即使這不是處理這種推薦的方式,快速的建議是重新添加這兩行你做setContentView(R.layout.intropage_landscape);

btnlogin = (Button)findViewById(R.id.btnlogin); 
btnlogin.setOnClickListener(this); 

推薦方式後:

  1. 不要爲每個方向調用setContentView。在onCreate中調用setContentView一次並初始化所有UI元素。
  2. 然後針對兩個方向重新使用通用UI元素
  3. 如果有一些非常見的UI元素,則根據需要使用片段進行添加和刪除。

希望這會有所幫助。

+0

whitch是這樣做的推薦方式...我在你建議和工作的這兩行之前嘗試,但我有太多複雜的代碼(重複行)。你建議更好的解決方案 – user3386169

+0

已編輯我的答案提出了一個更好的解決方案。請接受答案,如果它有助於你的情況。謝謝。 –

0

看起來您希望獲得有關方向更改的通知,但針對不同的方向保留不同的佈局。你的代碼中的問題很明顯 - setContentView設置了新的UI對象,並用它們的clicklistener刪除了舊對象。
建議:
- 從您的活動中移除configChanges標誌 - 因此您的活動將在每次旋轉後創建,
- 在您的onCreate get current screen orientation中,與以前的值(存儲在savedInstanceState中)
- 並將其保存在onSaveInstanceState(onCreate將收到方向改變後保存的包);
- 還將different orientations的活動佈局xml文件。