0

我正在使用片段活动。我的一项活动有一个微调器。我设置了它的适配器。问题是每当我切换到该活动时,微调器值都会增加。它实际上将相同的值添加到微调器中,而不会删除以前的值。如何解决?我的代码如下:

public class AddPackageFragment extends Fragment {

    View rootView; 
    EditText packageName;
    EditText packageNumber;
    Spinner network;
    CheckBox sim1;
    CheckBox sim2;
    RadioGroup type; 
    RadioGroup through;
    Button addPackage;
    Button actDetails;
    ArrayList<String> networks = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    Context context;

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

        rootView = inflater.inflate(R.layout.add_package, container, false);
        initializeViews();
        setNetworks();
        setSpinner();

        return rootView;
    }

    void initializeViews() {
        packageName = (EditText)rootView.findViewById(R.id.pName);
        packageNumber = (EditText)rootView.findViewById(R.id.pNumber);
        network = (Spinner)rootView.findViewById(R.id.networkS);
        sim1 = (CheckBox)rootView.findViewById(R.id.sim1);
        sim2 = (CheckBox)rootView.findViewById(R.id.sim2);
        type = (RadioGroup)rootView.findViewById(R.id.typeGroup);
        through = (RadioGroup)rootView.findViewById(R.id.throughGroup);
        addPackage = (Button)rootView.findViewById(R.id.addPackage);
        actDetails = (Button)rootView.findViewById(R.id.activationDetails);
        context = getActivity().getApplicationContext();
        addPackage.setActivated(false);
        actDetails.setActivated(false);
    }

    void setNetworks() {
        networks.add("Mobilink");
        networks.add("Telenor");
        networks.add("Ufone");
        networks.add("Warid");
        networks.add("Zong");
        networks.add("Add New");
    }

    void setSpinner() {
        adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, networks);
        network.setAdapter(null);
        network.setAdapter(adapter);
    }

}
4

2 回答 2

2

尝试这个:

void setNetworks() {
    networks.clear()
    networks.add("Mobilink");
    networks.add("Telenor");
    networks.add("Ufone");
    networks.add("Warid");
    networks.add("Zong");
    networks.add("Add New");
}

我认为这是因为您的阵列未清除,而不是微调器适配器。

于 2013-06-20T18:00:40.340 回答
1

详细说明@Dimmerg

根据 Fragment 生命周期,您onCreateView将被多次调用。因此,您必须考虑到这一点并相应地清除值(或列表)。

片段生命周期

于 2013-06-20T18:02:57.617 回答