android-fragments 如何在Android Studio中将Activity转换为片段

ca1c2owp  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(152)

有人能告诉我我是怎么做的吗?或者有人能为我把这个活动改成片段。我现在在编码方面的经验很少,所以我不能自己做这个。

public class SplashActivity extends AppCompatActivity {

FirebaseAuth auth;
FirebaseUser user;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    auth=FirebaseAuth.getInstance ();
    user=auth.getCurrentUser ();

    new Handler(  ).postDelayed (new Runnable () {
        @Override
        public void run() {
            if (user !=null)
            {
                startActivity ( new Intent( SplashActivity.this,HomeActivity.class ) );
            }
            else
            {
                startActivity ( new Intent ( SplashActivity.this,Login.class ) );
            }
            finish ();
        }
    },1500 );
}

}

j8ag8udp

j8ag8udp1#

我会从理解它们的生命周期(activity和fragment)开始。然后我们就可以很好地了解将代码从activity中的onCreate()移动到Fragment中的onViewCreated()的位置。还要注意,activity扩展了AppCompatActivity,而Fragment扩展了Fragment类。有了这两个观察,我们现在可以继续如下所述。注意,由于从activity到类的更改,布局和类的重命名。

class SplashFragment extends Fragment {
    private FirebaseAuth auth;
    private FirebaseUser user;

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

        auth = FirebaseAuth.getInstance ();
        user = auth.getCurrentUser ();

        return inflater.inflate(R.layout.fragment_splash, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        new Handler().postDelayed (new Runnable () {
            @Override
            public void run() {
                //Do your logic here.
            }
        }, 1500);
    }
    
}

参考文献:片段生命周期:https://developer.android.com/guide/fragments/lifecycle片段实现:https://developer.android.com/guide/fragments/create

相关问题