我正在按照一個(gè)博客的教程來創(chuàng)建片段。我創(chuàng)建了三個(gè)片段,但是當(dāng) Mainactivity 加載時(shí)......它是空的,并且只有當(dāng)單擊抽屜菜單中的任何項(xiàng)目時(shí),才會(huì)加載片段。我想在開始時(shí)加載任何片段[考慮 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();但它仍然在開始時(shí)不加載。提前致謝。
1 回答

守候你守候我
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
不需要?jiǎng)?chuàng)建fragment實(shí)例,onCreate您可以刪除以下行
fragment = new ConnectFragment();
簡而言之,您應(yīng)該像下面這樣調(diào)用selectItem()內(nèi)部方法。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
}
添加回答
舉報(bào)
0/150
提交
取消