【问题标题】:orientation change getting the same layout in fragment方向改变在片段中获得相同的布局
【发布时间】:2013-09-12 12:32:56
【问题描述】:

我正在将方向从纵向更改为横向,从横向更改为纵向。我的代码如下

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    //Set titlebar as "my@heaven"
    getSherlockActivity().getSupportActionBar()
    .setBackgroundDrawable(getResources().getDrawable(R.drawable.myheaven));

    view = inflater.inflate(R.layout.memorial_listing, container, false);   

    setUpView(savedInstanceState);

    return view;
}

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {


    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){

    }

  }

我也将它添加到清单中

android:configChanges="orientation|keyboardHidden|screenSize"

我将相同的布局放在纵向布局文件夹和横向布局土地中,但是当我尝试旋转屏幕时,如果从纵向开始,则仍会从布局文件夹中获取布局。屏幕旋转但没有获得正确的文件夹来显示布局。请帮忙

【问题讨论】:

标签: java android


【解决方案1】:
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Get a layout inflater (inflater from getActivity() or getSupportActivity() works as well)
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if(// new orientation is potrait){
        // load potrait layout
    }else{
       // load landscape layout
    }
}

此方法在方向改变时接收回调。所以在接收回调时膨胀布局。

P.S:两个布局应该有不同的名称。不要将横向布局放在 layout-land 文件夹中。当我遇到这个问题时,我不得不从 layout-land 中拉出我的布局并将其放入 layout 文件夹中。虽然这不是一个好的做法,但在我的情况下,它只是这样工作的。

【讨论】:

  • 我像你一样遵循这种方式。是的,布局已更改,但数据仍为空。请指教
  • @nick 如果您正在使用一些 D.S,如 arraylist/其他任何东西,您可以重用它,因为数据会在那里,您可以使用该数据重新填充视图。在我的情况下,我收集了业务对象,并且在方向更改时保留了这些对象。因此,我重用了该集合并重新填充了我的视图。如果您找到更好的方法,请分享。
  • 如果我只想更改布局但不重新填充整个数据集,是否可行?
  • 使用inflater.inflate(...) 更改布局。您可能必须使用((ViewGroup) getView()).removeAllViews(); 删除所有视图,然后添加由inflate(...) 返回的返回视图,例如((ViewGroup)getView()).addView(view);
  • 是的,如果从布局文件夹中获取纵向,如果从布局文件夹中获取横向,则我尝试更改此布局。但没有加载数据。空布局
【解决方案2】:

以下对我有用,

if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){

    Log.e("On Config Change","LANDSCAPE Mode");
}else{

    Log.e("On Config Change","PORTRAIT Mode");
}

你能检查一下吗?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多