为了账号安全,请及时绑定邮箱和手机立即绑定

活动开始时加载片段

活动开始时加载片段

守着星空守着你 2023-09-27 16:52:29
我正在按照一个博客的教程来创建片段。我创建了三个片段,但是当 Mainactivity 加载时......它是空的,并且只有当单击抽屉菜单中的任何项目时,才会加载片段。我想在开始时加载任何片段[考虑 ConnectFragment]。这是我的代码public class MainActivity extends AppCompatActivity {    private String[] mNavigationDrawerItemTitles;    private DrawerLayout mDrawerLayout;    private ListView mDrawerList;    Toolbar toolbar;    private CharSequence mDrawerTitle;    private CharSequence mTitle;    android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;    Fragment fragment = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTitle = mDrawerTitle = getTitle();        mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);        mDrawerList = (ListView) findViewById(R.id.left_drawer);        setupToolbar();        fragment = new ConnectFragment();        DataModel[] drawerItem = new DataModel[3];        drawerItem[0] = new DataModel(R.drawable.connect, "Connect");        drawerItem[1] = new DataModel(R.drawable.fixtures, "Fixtures");        drawerItem[2] = new DataModel(R.drawable.table, "Table");        getSupportActionBar().setDisplayHomeAsUpEnabled(false);        getSupportActionBar().setHomeButtonEnabled(true);        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);        mDrawerList.setAdapter(adapter);        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);        mDrawerLayout.setDrawerListener(mDrawerToggle);        setupDrawerToggle();    }我尝试过            fragment = new ConnectFragment();但它仍然在开始时不加载。提前致谢。
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

不需要创建fragment实例,onCreate您可以删除以下行


fragment = new ConnectFragment();

简而言之,您应该像下面这样调用selectItem()内部方法。onCreate()


@Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // .....

        setupDrawerToggle();

        // here you need call selectItem() method 

        selectItem(0) // you can change default fragment by changing parameter (0/1/2) as you want

    }


查看完整回答
反对 回复 2023-09-27
  • 1 回答
  • 0 关注
  • 98 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信