2016-09-23 4 views
0

Я пытаюсь использовать панель навигации и открывать с ней новые фрагменты. Я просмотрел все вопросы об этом и просмотрел много видео на YouTube ... но я не могу понять, почему содержимое фрагмента не появляется. Вот код:Фрагмент не отображается

MainActivity класс:

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener, MainFragment.OnFragmentInteractionListener, OtherFragment.OnFragmentInteractionListener { 

    NavigationView navigationView; 
    Toolbar toolbar; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

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

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 

     if (id == R.id.nav_camera) { 
      MainFragment frag = new MainFragment(); 
      FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
      ft.replace(R.id.fragment_container, frag).commit(); 
     } else if (id == R.id.nav_gallery) { 
      OtherFragment frag = new OtherFragment(); 
      FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
      ft.replace(R.id.fragment_container, frag); 
      ft.commit(); 
     } else if (id == R.id.nav_slideshow) { 

     } else if (id == R.id.nav_manage) { 

     } else if (id == R.id.nav_share) { 

     } else if (id == R.id.nav_send) { 

     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if(drawer!=null) 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    @Override 
    public void onFragmentInteraction(Uri uri) { 

    } 

} 

MainFragment класса (равно OtherFragment класс):

public class MainFragment extends Fragment { 
    // TODO: Rename parameter arguments, choose names that match 
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
    private static final String ARG_PARAM1 = "param1"; 
    private static final String ARG_PARAM2 = "param2"; 

    // TODO: Rename and change types of parameters 
    private String mParam1; 
    private String mParam2; 

    private OnFragmentInteractionListener mListener; 

    public MainFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_main, container, false); 
    } 

    // TODO: Rename method, update argument and hook method into UI event 

    /** 
    * This interface must be implemented by activities that contain this 
    * fragment to allow an interaction in this fragment to be communicated 
    * to the activity and potentially other fragments contained in that 
    * activity. 
    * <p> 
    * See the Android Training lesson <a href= 
    * "http://developer.android.com/training/basics/fragments/communicating.html" 
    * >Communicating with Other Fragments</a> for more information. 
    */ 
    public interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     void onFragmentInteraction(Uri uri); 
    } 
} 

app_bar_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context=".MainActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

    <FrameLayout 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

    </FrameLayout> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|end" 
     android:layout_margin="@dimen/fab_margin" 
     app:srcCompat="@android:drawable/ic_dialog_email" /> 

</android.support.design.widget.CoordinatorLayout> 

fragment_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="de.package.test.MainFragment"> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:text="@string/hello_blank_fragment" /> 

</FrameLayout> 

У меня нет кодов ошибок. Я был бы очень рад, если бы вы могли мне помочь;)

+1

Вы когда-нибудь шаг за шагом отлаживали свой код? Это должно дать вам ответ почти сразу. –

+0

Что именно вы имеете в виду? – Tim

+0

https://developer.android.com/studio/debug/index.html –

ответ

-1

Вы предоставили контейнер фрагмента в координатореLayout цвет фона, чтобы увидеть, даже если он появляется?

Также вы должны сделать метод переключателя фрагментов, который принимает фрагмент вместо вашей ситуации if-else с повторяющимся кодом транзакции.

+0

Да, я просто протестировал его, показывается контейнер фрагментов в app_bar, но не его содержимое. Что-то еще не обязательно. – Tim

+0

Справа. Я говорю, что хорошая практика заключается в использовании переключателя фрагментов, поэтому у вас нет избыточного кода. – user2892437

Смежные вопросы