2016-05-31 1 views
1

이 문제에 관해 많은 것을 발견했지만 실제로 문제를 해결할 수 없습니다. 나는 이것에 시간을 보냈지만 아무것도하지 않았다.탐색 서랍 항목에서 조각을로드 할 수 없습니다.

Android Studio 2.1.1 템플릿으로 만든 탐색 창 활동이 있습니다. 물론 메뉴에서 항목을 클릭 할 때 내 앱의보기를 변경하여 다른 단편을 표시하고 싶습니다. 내가 탐색 함 (아이디 R.id.nav_camera와 하나)의 첫 번째 항목을 클릭하면

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

     if (id == R.id.nav_camera) { 

      Context context = getApplicationContext(); 
      CharSequence text = "Hello toast!"; 
      int duration = Toast.LENGTH_SHORT; 

      Toast toast = Toast.makeText(context, text, duration); 
      toast.show(); 

      new gaussFragment(); 

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

     } 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); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

내가 토스트하지만 새로운 조각이 표시되지 않는 볼 수 있습니다 : 이것은 내가 MainActivity에있는 코드입니다. 나는 gaussFragment()에서이 코드를 사용하고 있습니다 :

당신이 here fragment_gauss.xml 볼 수있는 상대 레이아웃이 코드를 가지고있다으로 물론
public class gaussFragment extends Fragment { 

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

} 

:

<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="info.androidhive.tabsswipexx.gaussFragment"> 

    <!-- TODO: Update blank fragment layout --> 
    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="@string/hello_blank_fragment" /> 

</FrameLayout> 

어떻게이 문제를 해결할 수?


content_main은 앱이 시작될 때 가장 먼저 나타납니다.

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

등을 추가해야하며 어떻게 든 내 조각을로드해야합니까?

+0

확인 탐색 서랍에 선택 될 때마다 표시되는 제대로 처리, 당신은 새로운 조각기로했다 d가 즉시 가비지 수집되었습니다 ... FrameLayout에로드하려면 FragmentTransaction이 필요합니다. –

+0

어떻게 코딩 할 수 있습니까? –

+0

[documentation] (https://developer.android.com/training/basics/fragments/fragment-ui.html)이 도움이되는지 확인한 다음 질문이있는 경우 다시보십시오. –

답변

2

은 탐색 서랍 주요 활동 XML의 다음 안드로이드 스튜디오에서 제공하는 내비게이션 창 템플릿을 사용하는 경우 당신은 같은 것을 찾을 수 있습니다 : 당신이 볼 당신이 가까이가 보면 걸릴 경우

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayout 
    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:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:openDrawer="start"> 

    <!-- The main content view --> 
    <include layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <!-- the navigation drawer the comes from the left--> 
    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 

     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer" /> 

</android.support.v4.widget.DrawerLayout> 

을 그것은 내가 당신을 위해 논평 한 두 가지 주요 부분으로 구성됩니다. 하나는 탐색 서랍 항목 용이고 다른 하나는 주요 내용보기 항목입니다.

<?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="copsonic.com.SoundExchange.demoApp.MainActivity"> 

    <!--Main View tool bar--> 
    <android.support.design.widget.AppBarLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     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> 

    <!--The content that will be displayed in the main view when the navigation drawer is not opened--> 
    <include layout="@layout/content_main" /> 

    <!--Floating Action Button Stuff--> 
    <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" 
     android:scaleType="center" 
     android:src="@mipmap/ic_rx_tx" 
     android:saveEnabled="false" 
     app:backgroundTint="#000000" 
     android:adjustViewBounds="false" /> 



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

는 3 개 주요 부품, 도구 모음 하나, 플로팅 작업 버튼 제어를위한 하나를 볼 수 있습니다 : 당신이 layout="@layout/app_bar_main" 클릭 + Ctrl을 경우 다른 XML은 다음과 인 열립니다 것을 볼 수 있습니다 마지막으로 내비게이션 창을 열지 않은 상태에서 기본보기에 표시 될 콘텐츠에 대한 내용입니다. 관심있는 내용입니다. <include layout="@layout/content_main" />에서 Ctrl + 클릭을하면 Fragmet 컨테이너를 추가해야한다는 세 번째 XML이 표시됩니다.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:showIn="@layout/app_bar_main" 
    tools:context="copsonic.com.SoundExchange.demoApp.MainActivity"> 

    <!-- A fragmet container to dynamically swap between fragmets--> 
    <FrameLayout 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</RelativeLayout> 

그래서이 모든 당신의 주요 활동 코드에서 당신은 단지 첫 번째, 두 가지를 먼저 볼 것입니다있는 조각 관리해야 후, 당신은 한 OnCreate 방법에서이 작업을 수행

: 결국은 같은 뭔가 추가 :

FragmentTransmitter initialFragment = new FragmentTransmitter(); 


// Check that the activity is using the layout version with 
// the fragment_container FrameLayout 
if (findViewById(R.id.fragment_container) != null) { 

     // this check allows you not to load the default fragment unless 
     //it's the first time you launch the activity after having destroyed it 
     if (savedInstanceState != null) { 
      return; 
     } 

    // Create the fragment that is seen the first time your app opens 

    //pass useful info to the fragment from main activity if needed 
    //(it is recommended not to do this in the constructor, so you have to do it through a Bundle) 
    Bundle args = new Bundle(); 
    args.putSerializable("ModulationType",aModulation); 
    initialFragment.setArguments(args); 


    // In case this activity was started with special instructions from an 
    // Intent, pass the Intent's extras to the fragment as arguments 
    //initialFragment.setArguments(getIntent().getExtras()); 

    // Add the fragment to the 'fragment_container' FrameLayout 
    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, initialFragment).commit(); 

} 

및 다음 두 번째 것은 조각이 옵션이

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

     if (id == R.id.nav_camera) { 

      Context context = getApplicationContext(); 
      CharSequence text = "Hello toast!"; 
      int duration = Toast.LENGTH_SHORT; 

      Toast toast = Toast.makeText(context, text, duration); 
      toast.show(); 

      FragmentTransmitter Gauss= new new gaussFragment(); 

      //pass useful info to fragment if needed 
      Bundle args = new Bundle(); 
      args.putSerializable(getString(R.string.ModulationType),aModulation); 
      Gauss.setArguments(args); 

      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
      transaction.replace(R.id.fragment_container, Gauss,"TAG_GaussFragment"); //pacing a tag is not mandatory but it is pretty useful if you want to know later which fragment is being displayed in the fragment container 
      //transaction.addToBackStack(null); 
      transaction.commit(); 



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

     } 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); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    }