2013-02-25 1 views
1

제 앱의 일부 상태를 저장하는 데 문제가 있습니다.상태 저장은 단편의 일부만 저장합니다.

레이아웃에서 i는 5 EditText, ButtonTextView입니다. 사용자가 값을 입력하고 계산 (단추 클릭)하면 TextView이 채워집니다.

방향이 바뀌면보기가 전달되어 완벽하게 작동하지만 스 와이프 (내 ViewPager)하면 채워진 상태 인 TextView이 저장되지 않습니다. 나는 3 조각을 가지고 있으며, 만약 내가 조각으로 돌아 왔을 때 TextView이 왼쪽으로 스 와이프하면, EditText에 입력 된 값이 저장됩니다.

내 계산에 따르면 (계산을 수행하고 TextView을 채우는 과정)이 저장되지 않는다면 어떻게해야합니까? 나는 어떤 행운도없이 Googles site에 관해 가이드 위에서 뒤쫓 으려고 노력했다.

내 코드는 간다 :

public class FuelConsumptionFragment extends Fragment implements OnClickListener { 


View view; 
int savedState = 0; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

} 


@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 

    if (savedInstanceState != null) { 

     savedState = savedInstanceState.getInt("curChoice", 0); 

    } 

} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("curChoice", savedState); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    view = inflater.inflate(R.layout.fuel_consumption, container, false); 

    Button calculate_fuel = (Button)view.findViewById(R.id.calculate_fuel); 
    calculate_fuel.setOnClickListener(this); 

    return view; 

    } 

매니페스트 :

<activity 
      android:name="simcas.fartberegneren.MainActivity" 
      android:icon="@drawable/fartberegneren" 
      android:label="" 
      android:configChanges="orientation|screenSize" > 
</activity> 

편집 : 내가 onCreateView의 인플레이션이 문제가 될 수 있다는 막연한 생각을 가지고,이 맞습니까?

편집 2 : 그냥 내 코드 주위에 가서 내 "사용자 정의"어댑터가 문제의 일부가 될 수 있음을 실현 코드는 간다 :

public class MyAdapter extends FragmentStatePagerAdapter { 

public MyAdapter(FragmentManager fm) { 
    super(fm); 

} 

@Override 
public int getCount() { 
    return 3; 
} 


@Override 
public Fragment getItem(int position) { 
    switch (position) { 
    case 0: return new SpeedZonesFragment(); 
    case 1: return new DistanceFragment(); 
    case 2: return new FuelConsumptionFragment(); 
    default: return null; 
    } 
} 
} 

이 문제를 일으킬 수 있을까? 내가 새로운 Fragment을 만들 때 위치를 바꿀 때 올바른지 확인하십시오.

편집 3 : onClick()에 대한 코드 :

@Override 
public void onClick(View view) { 

DecimalFormat format = new DecimalFormat("#.#"); 

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 

EditText distance_entry_fuel = (EditText) getActivity().findViewById(R.id.distance_fuel); 
EditText speed_a_entry_fuel = (EditText) getActivity().findViewById(R.id.speed_a_fuel); 
EditText gas_a_use = (EditText) getActivity().findViewById(R.id.gas_use_a); 
EditText speed_b_entry_fuel = (EditText) getActivity().findViewById(R.id.speed_b_fuel); 
EditText gas_b_use = (EditText) getActivity().findViewById(R.id.gas_use_b); 
EditText gas_price = (EditText) getActivity().findViewById(R.id.gas_price); 

distance_entry_fuel.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
speed_a_entry_fuel.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
gas_a_use.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
speed_b_entry_fuel.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
gas_b_use.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
gas_price.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 


distance_entry_fuel.clearFocus(); 
speed_a_entry_fuel.clearFocus(); 
gas_a_use.clearFocus(); 
speed_b_entry_fuel.clearFocus(); 
gas_b_use.clearFocus(); 

double moneySpend; 
double timeArest; 
double timeArest1; 
double timeBrest; 
double timeBrest1; 
double totalTime; 
double totalTimerest; 

try { 

    double distance = Double.parseDouble(distance_entry_fuel.getText().toString()); 
    double speedA = Double.parseDouble(speed_a_entry_fuel.getText().toString()); 
    double gasA = Double.parseDouble(gas_a_use.getText().toString()); 
    double speedB = Double.parseDouble(speed_b_entry_fuel.getText().toString()); 
    double gasB = Double.parseDouble(gas_b_use.getText().toString()); 
    double gasPrice = Double.parseDouble(gas_price.getText().toString()); 

    double gasUseA = (distance/gasA); 
    double gasUseB = (distance/gasB); 

    if (speedB > speedA) { 

     if (gasUseB > gasUseA) { 

      moneySpend = ((gasUseB - gasUseA) * gasPrice); 

     } 

     else { 

      moneySpend = ((gasUseA - gasUseB) * gasPrice); 

     } 

     timeArest = (distance % speedA); // Calculate the remainder of A 
     timeArest1 = ((timeArest/speedA) * 60); // Convert the remainder of A to minutes  
     timeBrest = (distance % speedB); // Calculate the remainder of B 
     timeBrest1 = ((timeBrest/speedB) * 60); // Convert the remainder of B to minutes 

     totalTime = (int)((distance/speedA) - (distance/speedB)); // Calculate the amount of hours saved    

     if (timeArest >= timeBrest) { // Condition for calculating time 

      totalTimerest = (timeArest1 - timeBrest1); 

     } 

     else {       // opposite condition 

      totalTimerest = ((timeArest1 - timeBrest1) + 60); // Make up for the negative number 

     }   

    } 

    else { 

     if (gasUseB > gasUseA) { 

      moneySpend = ((gasUseB - gasUseA) * gasPrice); 

     } 

     else { 

      moneySpend = ((gasUseA - gasUseB) * gasPrice); 

     } 

     timeArest = (distance % speedA); // Calculate the remainder of A 
     timeArest1 = ((timeArest/speedA) * 60); // Convert the remainder of A to minutes  
     timeBrest = (distance % speedB); // Calculate the remainder of B 
     timeBrest1 = ((timeBrest/speedB) * 60); // Convert the remainder of B to minutes 

     totalTime = (int)((distance/speedB) - (distance/speedA)); // Calculate the amount of hours saved 

     if (timeBrest >= timeArest) { // Condition for calculating time 

      totalTimerest = (timeBrest1 - timeArest1); 

     } 

     else {       // opposite condition 

      totalTimerest = ((timeBrest1 - timeArest1) + 60); // Make up for the negative number 

     } 
    } 

    String minuteTotal = ""; 
    String hourTotal = ""; 

    if (totalTimerest == 1) { 

     minuteTotal = " minut"; 

     } 

    else { 

     minuteTotal = " minutter"; 

    } 

    if (totalTime == 1) { 

     hourTotal = " time"; 

    } 

    else { 

     hourTotal = " timer"; 

    } 

    String moneySpendOnGas; 

    String distanceText = "Over en strækning på " + format.format(Double.parseDouble(distance_entry_fuel.getText().toString())) + " km"; 
    String gasUsedA = "Bruger du " + format.format(gasUseA) + " liter benzin, ved en gennemsnitsfart på " + speedA + " km/t."; 
    String gasUsedB = "Bruger du " + format.format(gasUseB) + " liter benzin, ved en gennemsnitsfart på " + speedB + " km/t."; 

    if (totalTime > 0) { 

     if (totalTimerest > 0) { 

      moneySpendOnGas = "Det koster dig " + format.format(moneySpend) + " kr at komme " + (int)totalTime + hourTotal + " og " + (int)totalTimerest + minuteTotal + " hurtigere frem."; 

     } 

     else { 

      moneySpendOnGas = "Det koster dig " + format.format(moneySpend) + " kr at komme " + (int)totalTime + hourTotal + " hurtigere frem."; 

     } 

    } 

    else { 

     moneySpendOnGas = "Det koster dig " + format.format(moneySpend) + " kr at komme " + (int)totalTimerest + minuteTotal + " hurtigere frem."; 

    } 

    TextView distance_text_fuel = (TextView) getActivity().findViewById(R.id.distance_text_fuel); 
    distance_text_fuel.setText(distanceText); 
    TextView gas_used_a = (TextView) getActivity().findViewById(R.id.gas_used_a); 
    gas_used_a.setText(gasUsedA); 
    TextView gas_used_b = (TextView) getActivity().findViewById(R.id.gas_used_b); 
    gas_used_b.setText(gasUsedB); 
    TextView money_spend = (TextView) getActivity().findViewById(R.id.money_spend); 
    money_spend.setText(moneySpendOnGas); 
} 

catch (NumberFormatException e) { 

    DialogFragment alert = new EntryAlertDialog(); 
    alert.show(getFragmentManager(), "Alert"); 

} 

} 
+0

'ViewPager.setOffscreenPageLimit (2)' –

+0

@vmironov :이 작업이 실제로 효과가 있었지만 상태를 저장하는 데 문제가 해결되지 않았으므로 fx에 뷰 파인더에 10 개의 조각이 있으면 엄청난 양을 사용하게됩니다 기억의 오른쪽? – Evilunclebill

+0

예. 'onSaveInstanceState'를 구현 한 다음 프래그먼트 상태를 적절히 복원해야합니다. –

답변

3

당신은 그 상태를 저장뿐만 아니라 EditTextTextView을 강제 할 수 있습니다. TextView.setFreezesText(true)으로 전화하거나 TextView 태그의 경우 android:freezesText="true"을 레이아웃 파일에 추가하면됩니다.

+0

이것은 매우 잘 작동했습니다. 감사합니다! – Evilunclebill