android - 保存状态只保存 fragment 的一部分

标签 android bundle

我在保存应用某些部分的状态时遇到了问题。

在布局中我有 5 个 EditText 一个 Button 和一个 TextView。当用户输入值并计算(单击按钮)时,将填充 TextView

当方向改变时没有任何反应, View 被传递并且完美地工作,但是当我滑动(使用我的 ViewPager)时填充的 TextView 的状态不是保存。我有 3 个 fragment ,如果我只滑动,比如从右到中,它会被保存,但是如果我滑动到最左边,当我返回到 fragment 时,TextView 没有填充,输入的值EditText 已保存。

我预计来自 onClick() 的过程(正在进行计算并填充 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;

    }

list :

<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");

}

}   

最佳答案

您可以像 EditText 一样强制 TextView 保存其状态。只需调用 TextView.setFreezesText(true) 或为布局文件中的 TextView 标记添加 android:freezesText="true"

关于android - 保存状态只保存 fragment 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15067890/

相关文章:

java - 如何在 apache karaf 中安装和运行 osgi bundle

ios - 设置不支持的语言时,CFBundleDevelopmentRegion不起作用

java - 单击时旋转 ImageView 属于 RecyclerView

java - 多行 TextView ,从第二行开始编辑?

android - 多平台 Cocos2d-x 项目

java - Activity State保存和恢复Helper

ruby-on-rails - 警告 : Running `gem pristine --all` to regenerate your installed gemspecs

android - onSaveInstanceState 是否应该保存 View 的 "enabledness"?

java - Android 无法在 AlertDialog 上获取消息对象

java - 将多个标记添加到谷歌地图并缩放以包含所有标记