[英]replace layout on orientation change
我的應用程序有一個webview和LinerLayout中的一些按鈕。
問題是,我希望按鈕在縱向模式下位於底部,而在橫向模式下位於左側,而webview保持其狀態。
兩種不同的布局不起作用,因為它迫使重新創建刷新Webview的活動。 現在,我在活動代碼中使用android:configChanges =“ orientation” ,以便不會在方向更改時刷新Webview 。
無論如何,是否可以在更改屏幕模式時替換按鈕的布局?
縱向模式
橫向模式
我測試了片段,但是處理片段會使事情變得更加復雜,並且片段本身需要保存和還原,這可能無法在具有javascript狀態的webview中工作,因此我搜索了更多內容,並在某處找到了不錯的文章,並進行了一些修改我建議的解決方案:
首先,添加android:configChanges="orientation|screenSize|keyboard|keyboardHidden"
以便該應用代替android處理配置更改。
為風景和肖像制作兩種不同的布局。 在這兩種布局中,代替Webview放置一個FrameLayout,該布局用作Webview的占位符。
定義如下initUI方法,並將與UI初始化相關的所有內容都放入此方法中:
public void initui()
{
setContentView(R.layout.main);
if (wv == null) wv = new WebView(this);
((LinearLayout)findViewById(R.id.webviewPlace)).addView(wv);
findViewById(R.id.home).setOnClickListener(this);
}
如果該webview不存在,則會創建它,並在setContentView(R.layout.main)
之后將其添加到布局中。 此后,您需要進行其他任何UI定制。
並在onConfigurationChanged
:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
((LinearLayout)findViewById(R.id.webviewPlace)).removeAllViews();
super.onConfigurationChanged(newConfig);
initUI();
}
在onConfigChange
將onConfigChange
從舊的占位符中刪除,並會調用initui
並將其重新添加到新的布局中。
在oncreate()
調用initui()
以便首次對ui進行初始化。
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initUI()
}
我希望這對某人有幫助。
如果您使用的是android:configChanges="orientation|screenSize"
在清單中,它忽略“ layout-land ”中的XML。 如果您為景觀創建其他XML,請不要為清單中的活動使用android:configChanges="orientation|screenSize"
標簽。
將其放置在您想要用作景觀的布局的layout-land
。
這個想法是,您不應該真正使用configChange="orientation"
因為它有缺點。 您可以在此處找到詳細的帖子。 如果要更改布局,則應手動處理狀態。 當然,您可以編程地執行此操作,但是如果您想使用xml來執行此操作。 您可以使用片段維護webView。
嘗試使用以下代碼:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_splash);
}
使您的視圖相對布局。 當方向改變時,只需為代碼中的每個視圖調整布局參數即可。 將按鈕包含在線性布局中
如..
肖像
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
buttonLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
buttonLinearLayout.setLayoutParams(lp);
LayoutParams webParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.ABOVE, R.id.buttons);
webView.setLayoutParams(webParams);
景觀
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
buttonLinearLayout.setOrientation(LinearLayout.VERTICAL);
buttonLinearLayout.setLayoutParams(lp);
LayoutParams webParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.TO_RIGHT_OF, R.id.buttons);
webView.setLayoutParams(webParams);
確保您使用的LayoutParams是RelativeLayout參數(始終使用視圖父級的Layoutparams)
您可以在資源下添加values-(所需的配置-例如land,portrait)文件夾,並提及此配置所需的布局。就這么簡單。
請查看以下鏈接以獲取更多信息-http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.