2015-06-01 3 views
0

В моем фрагменте, я хочу каждый пользовательский элемент в моей ListView, чтобы выглядеть следующим образом:Динамическое добавление элементов к уже созданным RelativeLayout

Имя

SetsXReps

[] [] [] [] [ ] ---> массив TextViews

[] [] [] [] [] ---> массив флажков

количество TextViews и флажков зависит от элемента адаптера, так что я необходимо динамически создавать эту часть. У меня возникли проблемы с динамическим добавлением этих элементов в мою релятивизацию, которую я частично определяю в своем xml. Вот мой класс фрагмента, за которым следует мой xml для элемента настраиваемого списка. Идентификатор макета - list_item_exercise_in_workout.

общественного класса WorkoutFragment расширяет фрагмент { общественности статической конечной строки EXTRA_ALREADYCREATED_ID = "shake2lift.nickdelnano.com";

private ExAdapter adapter; 
    private ListView listView; 
    private ArrayList<Set> sets; 
    private Workout w; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     UUID workoutId = (UUID) getArguments().getSerializable(EXTRA_ALREADYCREATED_ID); 
     w = WorkoutMASTER.get(getActivity()).getWorkout(workoutId); 

    } 


    public View onCreateView(LayoutInflater inflater, ViewGroup parent,Bundle savedInstanceState) 
    { 
     View v = inflater.inflate(R.layout.fragment_workout, parent, false); 

     adapter = new ExAdapter(getActivity(), R.layout.fragment_create_workout, R.id.list, sets); 
     listView.setAdapter(adapter); 

     return v; 

    } 
    public static WorkoutFragment newInstance(UUID workoutId) 
    { 
     Bundle args = new Bundle(); 
     args.putSerializable(EXTRA_ALREADYCREATED_ID, workoutId); 
     WorkoutFragment fragment = new WorkoutFragment(); 
     fragment.setArguments(args); 

     return fragment; 
    } 

    private class ExAdapter extends ArrayAdapter<Set> 
    { 
     public ExAdapter(Context c, int resource, int textViewResourceId, ArrayList<Set> sets) { 
      super(c, 0, sets); 
     } 

     public View getView(final int position, View convertView, ViewGroup parent) 
     { 

      //if we werent given a view, inflate one 
      if(convertView == null) 
      { 
       convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_exercise_in_workout, null); 

      } 
      Set s = getItem(position); 

      //RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
       //  RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 

      TextView name = (TextView) convertView.findViewById(R.id.exName); 
      name.setText(s.getName()); 
      TextView setsReps = (TextView) convertView.findViewById(R.id.setsXreps); 
      setsReps.setText(s.getSets() + "X" + s.getReps()); 

      CheckBox[] checkBoxes = new CheckBox[s.getSetsInt()]; 
      EditText[] weightBoxes = new EditText[s.getSetsInt()]; 
      //initialize weightBoxes's text to the inputted weight 
      for(int i = 0; i < weightBoxes.length; i++) 
      { 
       //code to add dynamically here 
      } 

      return convertView; 
     } 
    } 


} 

и мой XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/relativeLayoutEx" 
    > 
     <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Name" 
     android:id="@+id/exName" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 
    <TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:text="SetsXReps" 
    android:id="@+id/setsXreps" 
    android:layout_below="@id/exName" 
    android:layout_alignParentLeft="true" 
    /> 
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Button" 
    android:id="@+id/button2" 
    android:layout_below="@+id/setsXreps" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginTop="112dp" /> 

Я признателен за любую помощь или совет.

ответ

0

Вы должны сначала получить указатель на свой RelativeLayout как этот

RelativeLayout container = (RelativeLayout) view.findViewById(R.id.relativeLayoutEx); 

Затем в течение цикла, создавать текстовые поля (и флажков) динамически и добавить их в макете:

TextView text = new TextView(getActivity()); 
text.setText("Hello"); 
container.addView(text); 
Смежные вопросы