简体   繁体   中英

Add and remove multiple views

Currently I am trying to add multiple instances of the same view to a viewgroup, I want to give my users the ability to remove these added views if necessary, but I am not sure how to reference each view individually.

How can I keep track of each view seperately, and if necessary reference each one to retrieve individual data from edit texts/spinners?

onCreateView()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_create, container, false);
    initValues();
    return view;
}

Inside init()

This is how I am trying to use the view which will be added, and how I am gaining access to the button.

    inflater = getActivity().getLayoutInflater();
    singleWorkout = inflater.inflate(R.layout.single_workout_layout, workoutLayout, false);
    btnRemoveWorkout = (Button) singleWorkout.findViewById(R.id.btnRemoveWorkout);
    btnRemoveWorkout.setOnClickListener(this);

OnClick()

This is how I am adding the views programmatically.

 inflater = getActivity().getLayoutInflater();
 singleWorkout = inflater.inflate(R.layout.single_workout_layout, workoutLayout, false);
 workoutLayout.addView(singleWorkout);


 spinnerWorkoutGroup = (Spinner) singleWorkout.findViewById(R.id.spinnerWorkoutGroup);
 array = getActivity().getResources().getStringArray(R.array.string_array_muscle_groups);
 TextSpinnerAdapter adapter2 = new TextSpinnerAdapter(getActivity(), R.layout.spinner_text_item, array);
            // Specify the layout to use when the list of choices appears
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // Apply the adapter to the spinner
            spinnerWorkoutGroup.setAdapter(adapter2);

OnClick() removeWorkout Button

This does not work at all.

 case R.id.btnRemoveWorkout:
                Log.e("BTN PRESSED", "BTN PRESSED");
                inflater = getActivity().getLayoutInflater();
                singleWorkout = inflater.inflate(R.layout.single_workout_layout, workoutLayout, false);
                workoutLayout.removeView(singleWorkout);
                break;

What you need is ListView & adapter pattern, you can add, remove items your adapter & call yourAdapter.notifyDataSetChanged(); when needed. It will refresh your view itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM