0

3 조각 (조각 홈, 조각 A, 조각 B 및 단편 C)이 있습니다. 앱을 처음 실행하면 Fragment Home (Mainactivity에 설정 됨)이 표시됩니다. From Drawing Draw Item은 모든 조각을 선택할 수 있습니다. 선택한 모든 항목에 세부 조각이 표시됩니다.Fragment에서 화면을 회전하고 데이터를 저장하는 방법은 무엇입니까?

I는 데이터를 처리하고 단편을 유지하는 문제를 가지고

(1). 조각을 선택하면 (예 : 조각 A) 조각 A의 페이지가 표시됩니다. 그러나 장치를 회전 할 때 조각이 원래 조각으로 돌아가고 현재 조각에 머물러 있지 않은 이유는 무엇입니까?

(2). 단편 B에서는 GridView에 이미지를 표시합니다. 그러나 장치를 회전 할 때 왜 내 조각이 조각 홈으로 돌아가고 현재 조각에는 머물러 있지 않은지 ?? 조각을 처리하고 여전히이 조각을 기존 데이터로 표시합니까? 당신은 당신의 조각 A와 B에 onConfigurationChanged(Configuration newConfig) 메소드를 오버라이드 (override) 할 필요가

public class FragmentB extends Fragment { 
private static final String LOG_TAG = FragmentB.class.getSimpleName(); 

private ImageAdapter imageAdapter; 
private ArrayList<Movie> movieList; 

public FragmentNowPlaying() { 
    super(); 
} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setRetainInstance(true); 
} 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_b, container, false); 
    GridView gridView = (GridView) rootView.findViewById(R.id.gridviewNowPlaying); 

    imageAdapter = new ImageAdapter(getContext(), R.layout.fragment_b, movieList); 
    if (savedInstanceState == null) { 
     movieList = new ArrayList<Movie>(); 
    }else{ 
     movieList = (ArrayList<Movie>) savedInstanceState.get("MovieList"); 
    } 

    gridView.setAdapter(imageAdapter); 
    return rootView; 
} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    outState.putParcelableArrayList("MovieList",movieList); 
    super.onSaveInstanceState(outState); 
} 
+0

시도 설정 'setRetainInstance (참)' [정확히 retainStateTrue()에서 발생 (http://stackoverflow.com/questions/12640316/further-understanding-setretaininstancetrue) –

+0

@EmdadHossain 이미 시도했지만 여전히 수 없습니다. 몇 가지 예를들 수 있습니까? –

답변

0

:

public class MainActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener { 

private static final String LOG_TAG = MainActivity.class.getSimpleName(); 

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

    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 = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 

    displaySelectedItem(R.id.nav_home); 
} 

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

    return true; 
} 

private void displaySelectedItem (int itemId) { 
    Fragment fragment = null; 

    switch (itemId){ 
     case R.id.nav_home: 
      fragment = new FragmentHome(); 
      break; 
     case R.id.nav_a: 
      fragment = new FragmentA(); 
      break; 
     case R.id.nav_b: 
      fragment = new FragmentB(); 
      break; 
     case R.id.nav_c: 
      fragment = new FragmentC(); 
      break; 
     case R.id.nav_d: 
      fragment = new FragmentD(); 
      break; 
    } 

    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager(); 
    List<Fragment> fragments = fragmentManager.getFragments(); 
    if (fragments != null) { 
     for(Fragment f : fragments){ 
      fragmentManager.popBackStack(); 

     } 
    } 


    //replace the fragment 
    if (fragment != null) { 
     FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.content_frame, fragment, "TAG_FRAGMENT"); 
     fragmentTransaction.commit(); 
    } 

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawerLayout.closeDrawer(GravityCompat.START); 
} 

조각 A : :

public class FragmentA extends Fragment { 
public FragmentA() { 
    super(); 
} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setRetainInstance(true); 
} 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_a, container, false); 
    return rootView; 
} 

@Override 
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 
    getActivity().setTitle("Fragment A"); 
} 
} 

조각 B


내 코드입니다 앱 구성시 거기에 머물러있게 해달라고 n 변경. 예 :

 @Override 
     public void onConfigurationChanged(Configuration newConfig) { 
       super.onConfigurationChanged(newConfig); 
       // get current fragment 
       Fragment fragment = mAdapter.getItem(currentItem); 
       if(fragment!=null){ 
        fragment.onResume(); 
       } 
     } 
0

화면을 회전 할 때마다 onCreate() 메서드가 호출되기 때문에.

일)() 에서 onCreate()는 savedInstanceState (여부 방법 검사에서

주위에 널 (null)인지

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if(null == savedInstanceState){ 
      //set you initial fragment object 
     } 
    else 
     { 
     //Load the fragment by tag 
     } 
    } 

그냥 onPause 전에 인스턴스 상태를 저장하기 모든 단편에서

@Override 
protected void onSaveInstanceState(Bundle bundle1) 
{ 
super.onSaveInstanceState(bundle1); Log.i(tag,"inside onSaveInstanceState");  
bundle1.putInt("tag",n); 

} 
0

이 문제가 해결되었습니다. MainActivity에서 다음을 추가하십시오 :

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); 
} 

@Override 
protected void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0); 
    Menu menu = navigationView.getMenu(); 
    menu.getItem(mCurrentSelectedPosition).setChecked(true); 
} 

모든 조각에 추가 된 조건이 savedInstanceState를 확인하십시오. 조각의

감사합니다 모두