2013-11-27 5 views
3

다음은이 질문의 후속 조치입니다. ViewPager and fragments — what's the right way to store fragment's state?. 코드에서이 부분을 해석 할 사람이 필요합니다.뷰 페이지의 뷰 상태 저장

Another approach is to override FragmentPageAdapter.instantiateItem(View, int) and save a reference to the fragment returned from the super call before returning it (it has the logic to find the fragment, if already present).

나는 viewpager로 커서에서 데이터를로드 할 PagerAdapter를 사용하여 사용하고 있습니다. 이미 PagerAdapter.intantiateItem을 재정의했습니다. 클릭해야하는 Button의 상태를 저장할 수 있어야합니다. 이것은 내 코드

public class CustomQuestionPagerAdapter extends PagerAdapter { 

private Cursor cursor; 
private Cursor cursorCategory; 
private LayoutInflater inflater; 
private Context context; 
private ArrayList<String> optionsArray; 
String rightAnswer; 
String wrongAnswer1; 
String wrongAnswer2; 
Button option1; 
Button option2; 
Button option3; 

public CustomQuestionPagerAdapter(Context context, Cursor cursor1, Cursor cursor2) { 
    this.context = context; 
    this.cursor = cursor1; 
    this.cursorCategory = cursor2; 
    this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

}   

public void swapCursor(Cursor cursor) { 
    this.cursor = cursor; 
} 

public void swapAnotherCursor(Cursor cursor) { 
    this.cursorCategory = cursor; 
} 


public void destroyItem(View view, int position, Object object) { 
    ((ViewPager) view).removeView((ScrollView) object); 
} 

@Override 
public int getCount() { 
    if (cursor == null) { 
     return 0; 
    }else { 
     return cursor.getCount(); 
    } 
} 



/* (non-Javadoc) 
* @see android.support.v4.view.PagerAdapter#instantiateItem(android.view.View, int) 
*/ 


@Override 
public Object instantiateItem(View view, int position) { 

    cursor.moveToPosition(position); 
    final ViewPager pager = (ViewPager) view.findViewById(R.id.pager_nav); 
    ScrollView layout = (ScrollView) inflater.inflate(R.layout.question_activity, null); 
    if (cursorCategory != null && cursorCategory.moveToFirst()){ 
     String s = cursorCategory.getString(cursorCategory.getColumnIndex("name")); 
     ((TextView)layout.findViewById(R.id.text_category)).setText(s); 
    } 

    Typeface tpf = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf"); 
    String text = cursor.getString(cursor.getColumnIndex("question_text")); 
    TextView question_text = (TextView)layout.findViewById(R.id.text_question); 
    question_text.setText(text); 
    question_text.setTypeface(tpf); 

    String qPos = Integer.toString(position + 1) + "."; 
    TextView question_position = (TextView) layout.findViewById(R.id.text_position); 
    question_position.setText(qPos); 
    question_position.setTypeface(tpf); 

    this.rightAnswer = cursor.getString(cursor.getColumnIndex(DBHelper.RIGHT_ANSWER)); 
    this.wrongAnswer1 = cursor.getString(cursor.getColumnIndex(DBHelper.WRONG_ANSWER1)); 
    this.wrongAnswer2 = cursor.getString(cursor.getColumnIndex(DBHelper.WRONG_ANSWER2)); 

    optionsArray = new ArrayList<String>(); 
    optionsArray.clear(); 
    optionsArray.add(this.rightAnswer); 
    optionsArray.add(this.wrongAnswer1); 
    optionsArray.add(this.wrongAnswer2); 
    Collections.shuffle(optionsArray); 

    option1 = (Button) layout.findViewById(R.id.button_option1); 
    option1.setText((CharSequence) this.optionsArray.get(0)); 

    option2 = (Button) layout.findViewById(R.id.button_option2); 
    option2.setText((CharSequence) this.optionsArray.get(1)); 

    option3 = (Button) layout.findViewById(R.id.button_option3); 
    option3.setText((CharSequence) this.optionsArray.get(2)); 


    final Button next = (Button) layout.findViewById(R.id.next_button); 
    next.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      int j = getItem(+1) + 1; 
      Toast.makeText(context, context.getResources().getString(R.string.question_no) + " " + j, Toast.LENGTH_SHORT).show(); 
      pager.setCurrentItem(getItem(+1), true); 
      next.setBackgroundColor(0xffeeeeee); // i need to save this new bacground color 
     } 

     private int getItem(int i) { 
      return i += pager.getCurrentItem(); 
     } 
    }); 

나도이 대답을 시도했지만 사전에 Saving Fragment state in ViewPager

감사를 작동하지 않았다이다.

+1

원하는 데이터를 저장하기 위해 환경 설정을 사용하지 않으시겠습니까? – Techfist

답변

1

shared pref에 클릭 한 button_id를 동적으로 저장합니다. 이미 모든 작업을 완료 했으므로 공유 상태에서 단추 상태를 복원해야하며 단추를 클릭 할 때 공유 된 기본 설정에서 단추를 추가하십시오.
업데이트 :

public static final String PREFS_NAME = "MyPrefsFile"; 
------ 
final Button next = (Button) layout.findViewById(R.id.next_button); 
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     boolean isClicked = settings.getBoolean(getCurrentItemPosition(), false); 
     if(isClicked) 
     { 
     next.setBackgroundColor(0xffeeeeee); 
     } 

    next.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      int j = getItem(+1) + 1; 
      Toast.makeText(context, context.getResources().getString(R.string.question_no) + " " + j, Toast.LENGTH_SHORT).show(); 
      pager.setCurrentItem(getItem(+1), true); 
      // i need to save this new bacground color 
     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean(getCurrentItemPosition(), true); 
     editor.commit(); 
     } 

     private int getItem(int i) { 
      return i += pager.getCurrentItem(); 
     } 
    }); 

getCurrentItemPosition() 현재 itemposition입니다.

+0

몇 가지 코드를 얻을 수 있다면 감사하겠습니다. sharedPreferences 개념을 이해하고 프로젝트의 다른 부분에서 사용했지만 각보기에 대해 button_id를 얻는 방법을 모르겠습니다. 감사. – Jimi

+0

당신은 호출기 View_Id와 해당하는 button_id-> Now를 공유 프리프 파일에 저장하면 'viewId_buttonId'와 같은 사용자 정의 형식으로 저장하고, 복원 할 때 button_id와 view_id가 일치하면 복원하십시오. 내 요점이있어? – Yup

+0

불행히도, 나는 그렇지 않습니다. – Jimi

1

PagerAdapter은 상태 복원시보기를 자동으로 저장 및 복원하지 않습니다.
보기의 경우 FragmentStatePagerAdapter과 동일해야합니다. 직접 구현할지 또는 이미 사용 가능한 구성 요소를 확장할지 여부를 선택할 수 있습니다. GitHub에는 몇 가지가 있습니다 : 예 : https://github.com/NightlyNexus/ViewStatePagerAdapter.
뷰 홀더를 재활용해야한다면 위대한 Jake Wharton https://github.com/JakeWharton/salvage의 뷰 페이저 어댑터도 있습니다. 필자는 전자를 더 잘 적합하다고 생각 했으므로 PageAdapter을 새 ViewStatePagerAdapter으로 바꿔 createView(ViewGroup, int)destroyView(ViewGroup, int)으로 바꿉니다.
예제를 확인하는 것이 쉽습니다.