android 如何在运行时将片段的屏幕方向锁定为横向

ni65a41a  于 2023-10-14  发布在  Android
关注(0)|答案(6)|浏览(113)

我有一个Activity,它的ist片段被设置为普通的potrait方向,但在加载第二个片段时,我需要将第二个片段的方向锁定为landscape。有可能吗?
这是我的java片段类

public class DeputationsFragment extends Fragment implements AdapterView.OnItemSelectedListener{
    LinearLayout ll;
    RecyclerView recyclerView;
    SessionManager sessionManager;
    CheckBox checkBox;
    Spinner reportType;
    String[] reportTypes,reportCodes;
    String reportCode;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        return inflater.inflate(R.layout.fragment_deputations, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sessionManager=SessionManager.NewInstance(getActivity());
        ll=(LinearLayout)view.findViewById(R.id.ll1);
        recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        checkBox=(CheckBox)view.findViewById(R.id.sno);
        reportType=(Spinner)view.findViewById(R.id.spin_report);
        reportType.setOnItemSelectedListener(this);
        if(Constants.isOnline())
        {
            getTypes();
        }

    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        reportCode=reportCodes[i];
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    private void getTypes()
    {
        AsyncHttpClient client=new AsyncHttpClient();
        String url=getResources().getString(R.string.urlReportType);
        Constants.showProgress(getActivity());
        client.get(url, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Constants.dismissProgress();
                try {
                    int p1 = responseString.indexOf(">"); Constants.dismissProgress();
                    Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
                    int p2 = responseString.lastIndexOf("<");
                    String r = responseString.substring(p1 + 1, p2);
                    p1 = r.indexOf(">");
                    r = r.substring(p1 + 1, r.length());
                    JSONArray jsonArray = new JSONArray(r);
                    reportTypes = new String[jsonArray.length()];
                    reportCodes = new String[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        reportTypes[i] = (jsonObject.getString("Name"));
                        reportCodes[i] = (jsonObject.getString("Value"));
                    }
                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, reportTypes);
                    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    reportType.setAdapter(arrayAdapter);
                    reportType.setSelection(0);
                    reportCode = reportCodes[0];
                    getDeputations();

                } catch (Exception e) {
                    Constants.dismissProgress();
                    Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
                }
            }
        });
        }

    void getDeputations()
    {
        Constants.showProgress(getActivity());
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        String url=getResources().getString(R.string.urlDeputationRequest);
        params.put("DistrictCode","ydRRTTxkdt6Trx91pX1+cA==");
        params.put("ReportType","1");
        client.get(url, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    Constants.dismissProgress();
                    int p1 = responseString.indexOf(">");
                    int p2 = responseString.lastIndexOf("<");
                    String r = responseString.substring(p1 + 1, p2);
                    p1 = r.indexOf(">");
                    r = r.substring(p1 + 1, r.length());
                    JSONArray jsonArray = new JSONArray(r);
                    RecyclerDeputations recyclerDeputations=new RecyclerDeputations(jsonArray,getActivity());
                    ll.setVisibility(View.VISIBLE);
                    recyclerView.setAdapter(recyclerDeputations);
                    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

                }
                catch (Exception e)
                {

                }
            }
        });
    }

}

这是布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/ll"
        android:background="@color/colorAccent"
        android:layout_marginTop="10dp"
        android:weightSum="4">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_weight="1.7"
            android:gravity="right"
            android:padding="3dp"

            android:text="Report Type"
            android:textStyle="bold" />

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="30dp"
            android:layout_weight="2.3"
            android:gravity="left"
            android:padding="3dp"
            android:background="@color/white"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp">
            <Spinner
                android:id="@+id/spin_report"
                android:layout_width="match_parent"
                android:popupBackground="@color/white"
                android:gravity="left"
                android:layout_height="match_parent"
                android:textSize="8sp"
                android:scrollbars="horizontal"/>
        </RelativeLayout>
    </LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="8.5"
    android:background="#386FA5"
    android:id="@+id/ll1"
    android:orientation="horizontal">

    <CheckBox
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1.3"
        android:gravity="center_vertical"
        android:layout_gravity="start"
        android:text="All"
        android:background="@drawable/borders"
        android:id="@+id/sno"/>

    <TextView
        android:layout_width="0dp"
        android:text="S.No."
        android:gravity="start"
        android:layout_gravity="start"
        android:background="@drawable/borders"
        android:id="@+id/serial"
        android:textSize="12sp"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight=".5" />
    <TextView

        android:layout_width="0dp"
        android:text="Name"
        android:id="@+id/name"
        android:gravity="start"
        android:layout_gravity="start"
        android:textSize="12sp"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1" />
    <TextView

        android:layout_width="0dp"
        android:id="@+id/from"
        android:gravity="start"
        android:textSize="12sp"
        android:layout_gravity="start"

        android:text="From"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1.4" />
    <TextView

        android:layout_width="0dp"
        android:id="@+id/to"
        android:text="To"
        android:gravity="start"
        android:textSize="12sp"
        android:layout_gravity="start"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1.3" />

    <TextView

        android:layout_width="0dp"
        android:id="@+id/req_date"
        android:text="Request Date"
        android:gravity="start"
        android:textSize="12sp"
        android:layout_gravity="start"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1" />

    <TextView

        android:layout_width="0dp"
        android:id="@+id/pending"
        android:text="Pending With"
        android:gravity="start"
        android:textSize="12sp"
        android:layout_gravity="start"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1" />
    <TextView

        android:layout_width="0dp"
        android:id="@+id/remarks"
        android:text="Remarks"
        android:gravity="start"
        android:textSize="12sp"
        android:layout_gravity="start"
        android:background="@drawable/borders"
        android:padding="3dp"
      android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"/>
</LinearLayout>
9o685dep

9o685dep1#

我自己也实现了同样的功能。我的应用程序被锁定为肖像模式的所有片段,除了一个。为了实现正确的功能,我使用android:screenOrientation="nosensor"作为Activity(在Manifest文件中),以防止由于用户旋转设备而导致方向更改。
我还使用android:configChanges="keyboardHidden|orientation|screenSize"来防止Activity在方向更改时重新启动。否则,很容易陷入一个循环,Activity重新启动,进入正确的片段,再次改变方向,重复。
在片段的onResume()方法中,我调用getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);,在它的onPause()方法中,我调用getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
希望这对你有帮助!

tsm1rwdh

tsm1rwdh2#

在您的onCreate上尝试此操作,以便在activities or fragments上以编程方式设置Landscape

活动

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

碎片

在java中的rootView之后添加这一行

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
xn1cxnb4

xn1cxnb43#

Orientation属性是针对每个Activity的,因此您可以仅为包含片段的Activity声明方向,以便它处于横向中,其余Activity将保持原样。
因此,你需要设置方向在onscreen查看每个片段请检查下面的代码:
片段A

public class FragmentA extends Fragment {

        @Override

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

            View view = inflater.inflate(R.layout.fragment_a, container, false);
            changeFragmentOrientation();

            return view;

        }

    }

public void changeFragmentOrientation(){
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

片段B

public class FragmentB extends Fragment {

            @Override

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

                View view = inflater.inflate(R.layout.fragment_b, container, false);
                changeFragmentOrientation();

                return view;

            }

        }

    public void changeFragmentOrientation(){
    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
tpxzln5u

tpxzln5u4#

在第二个片段中调用setUserVisibleHint()函数,然后使用下面的代码

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser) {
        Activity curActivity = getActivity();
        if(curActivity != null){ 
             curActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
         }
     }
}
wlwcrazw

wlwcrazw5#

这是最好的选择。

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
    Activity a = getActivity();
    if(a != null)     a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
 }
}

祝你的项目好运:)

q1qsirdb

q1qsirdb6#

在manifest中添加android:Changes =“keyboardHidden|定向”
添加您的片段

@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getActivity() != null) {
        if (isViewProfileOrNot) {
            if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }

    }

}

相关问题