2013-07-08 17 views
0

我需要在運行時將按鈕添加到我的應用程序,但我想根據方向以不同的方式設置佈局。對於肖像,我希望寬度爲wrap_content,但在橫向上,我需要設置固定寬度。我知道如何單獨做這些工作,但我找不到任何方式使它們的工作方式與我在XML佈局文件中處理它的方式相同。可能嗎?以編程方式爲不同的方向添加具有不同屬性的按鈕

回答

0

我會檢查手機定位

getResources().getConfiguration().orientation 

並動態地添加按鈕參考

Dev

0

您需要首先將顯示實例:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 

然後取向可能會這樣調用:

int orientation = display.getOrientation(); 

然後你就可以創建一個不同的佈局,

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 
    int orientation = display.getOrientation(); 
    switch(orientation) { 
     case Configuration.ORIENTATION_PORTRAIT: 
      // ToDo layout for portrait 
      break; 
     case Configuration.ORIENTATION_LANDSCAPE: 
      // ToDo layout for landscape 
      break; 
    } 
} 

如果你想在運行時設置的方向,然後使用,

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT | ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 

創建像

 LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(android.widget.LinearLayout.VERTICAL); 
     ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1)); 
     // ARGB: Opaque Red 
     ll.setBackgroundColor(0x88ff0000); 

     TextView tv = new TextView(this); 
     tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2)); 
     tv.setText("sample text goes here"); 
     // ARGB: Opaque Green 
     tv.setBackgroundColor(0x5500ff00); 
     ll.addView(tv); 

     EditText et = new EditText(this); 
     et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2)); 
     et.setText("edit me please"); 
     // ARGB: Solid Blue 
     et.setBackgroundColor(0xff0000ff); 
     ll.addView(et); 

     Button btn = new Button(this); 
     btn.setText("Go!"); 
     btn.setOnClickListener(new Button.OnClickListener() { 
      public void onClick(View v) { 
       tv.setText(et.getText().toString()); 
      } 
     }); 

     ll.addView(btn); 
     setContentView(ll); 
佈局
相關問題