2017-10-07 34 views
0

我对Android非常陌生,我正在学习使用片段。我创建了一个片段,当我的BottomNavigation视图上的特定选项卡被选中时,它显示一个Textview。我打开片段是这样的:片段处于加载状态,从活动调用时不加载

public void switchToWorkoutFragment() { 
     FragmentManager manager = getSupportFragmentManager(); 
     manager.beginTransaction().replace(R.id.content, new 
      ListFragment()).commit(); 
    } 

然后我把这个功能,当“锻炼”按钮选择像这样:

private BottomNavigationView.OnNavigationItemSelectedListener 
mOnNavigationItemSelectedListener 
      = new BottomNavigationView.OnNavigationItemSelectedListener() { 

     @Override 
     public boolean onNavigationItemSelected(@NonNull MenuItem item) { 
      switch (item.getItemId()) { 
       case R.id.navigation_home: 
        mTextMessage.setText("Stats Fragment"); 
        return true; 
       case R.id.navigation_dashboard: 
        mTextMessage.setText("Workout Fragment"); 
        switchToWorkoutFragment(); 
        return true; 
       case R.id.navigation_notifications: 
        mTextMessage.setText("Goals Fragment"); 
        return true; 
      } 
      return false; 
     } 

    }; 

当我按下按钮锻炼,片段少了点想要加载。它无限期地与旋转图标坐在一起,不会加载任何东西。我不知道为什么它会这样做,因为没有那么多东西要加载(就像我说的,它只是一个文本视图)

回答

0

您是否将侦听器设置为视图? 像:

(BottomNavigationView) nav = findViewById(R.id.bottom_navigation_panel); 
nav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); 
+0

是的它在onCreate方法被设置在MainActivity } –

+0

使其成为FrameLayout或FragmentLayout而不是ListFragment。 – Shmuel

0

的问题是,你在switchToWorkoutFragment方法传递new ListFragment()。一个ListFragment包含一个ListView来显示这些项目,而这个ListView需要一个Adapter来拉取要显示的数据。既然你传递了一个全新的ListFragment而没有设置Adapter并传递数据来显示,那么Fragment没有任何东西可以显示。所以,你可以做这样的事情:

ListFragment fragment = new ListFragment(); 
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); 
adapter.addAll(Arrays.asList(new String[]{"Item one", "Item two", "Item 3"})); 
fragment.setListAdapter(adapter); 

getSupportFragmentManager() 
     .beginTransaction() 
     .add(R.id.fragmentContainer, fragment) 
     .commit(); 

注意,设置适配器足以隐藏纺纱图标,并正确显示ListFragment(有或无数据)

相关问题