每当我旋转屏幕时,它都会从片段屏幕跳转到主活动屏幕

时间:2017-05-25 06:21:10

标签: android android-fragments android-activity onsaveinstancestate onrestoreinstancestate

我是android的初学者,我用fragment创建了应用程序。当我旋转屏幕时(在片段屏幕中)它离开了片段屏幕并跳转到主活动屏幕。为什么?请帮我解决这个问题。 / p>

我的主要活动, 的 Individualuser_Safmical.java:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

我的片段, ShopFrgment.java:

public class IndividualUser_Safmical extends AppCompatActivity
         {
    FragmentManager fm;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
fm = getFragmentManager();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.i_activity_safmical);
}
 public void shopbycategory(View v) {
        fm.beginTransaction().replace(R.id.content_frame, new ShopFragment()).addToBackStack("shop").commit();

    }
}

3 个答案:

答案 0 :(得分:3)

您可以使用onConfigurationChanged

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

}

同时添加此行清单

android:configChanges="keyboardHidden|orientation|screenSize"

您可以通过在清单中添加此活动来锁定您的活动以避免方向更改

android:screenOrientation="portrait"

答案 1 :(得分:1)

查看保存活动状态并再次恢复示例。您必须在那里应用您的解决方案这是官方文档。 https://developer.android.com/guide/topics/resources/runtime-changes.html

答案 2 :(得分:0)

@Abdul Kawee写道

  

因为在旋转屏幕上活动被破坏并重新创建

他是正确的。有两种方法可以解决这个问题:

  1. Override Fragment的{​​{1}},onConfigurationChanged()onSaveInstanceState()回调方法。
  2. 或者您可以在应用的清单文件中添加onRestoreInstanceState()
  3. 有关详细信息,请参阅此SO Answer