如何在启动安卓应用时启动特定的片段?

问题描述 投票:1回答:2
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    BottomNavigationView bottomNavigationView;
    Fragment selectedFragment =  null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try
        {
            this.getSupportActionBar().hide();
        }
        catch (NullPointerException e){}

        setContentView(R.layout.activity_main);

        bottomNavigationView = (BottomNavigationView)
                findViewById(R.id.bottom_navigation);

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {


                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                        switch (item.getItemId()) {
                            case R.id.homee:
                                selectedFragment = new HomeFragment();
                                break;
                            case R.id.nav_search:
                                selectedFragment = new SearchFragment();
                                break;

                            case R.id.nav_notif:
                                selectedFragment = null;
                                startActivity(new Intent(MainActivity.this ,SearchFragment.class));
                                break;
                        }

                        if (selectedFragment != null){
                            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
                        }

                    return true;
                }
        });

    }

}

这都是我的主活动代码......我应该怎么做,才能让用户进入应用时默认打开主页片段,按照这个代码,当用户进入应用时,他需要按下主页按钮才能进入片段......我怎么能默认像例如instagram一样,用户一进来就把用户留在主页片段中,我怎么能这样做,我使用的是android材质的底部导航,如果你问我,我也可以提供这个活动的xml文件......谢谢你。

java android android-fragments fragment
2个回答
0
投票

在你的MainActivity onCreate方法中试试这个。

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_container, new ExploreMainFragment());
        ft.commit();

0
投票

在你设置好之后,试试这段代码 setOnNavigationItemSelectedListener

bottomNavigationView.getMenu().findItem(R.id. homee).setChecked(true)
© www.soinside.com 2019 - 2024. All rights reserved.