Я попытался найти примеры этой проблемы, но не могу найти ничего подходящего.Добавление динамически сгенерированных кнопок рядом друг с другом в LinearLayout
Что я хочу, это две кнопки рядом друг с другом, из автоматически созданного списка кнопок. Метод newAddButtonToLayout
- это моя попытка сделать что-то, что сделает это. Я получаю эту ошибку, когда я запускаю его:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
на row.addView(button)
Вот код вида деятельности:
package com.code.p2_project.finalevaluationapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import java.util.ArrayList;
public class ExerciseList extends Activity implements View.OnClickListener {
private ArrayList<Exercise> list = new ArrayList<Exercise>();
//This array holds the exercises
private ArrayList<Button> buttons = new ArrayList<Button>();
//This array holds the buttons
private ArrayList<Exercise> exercises = new ArrayList<Exercise>();//store them in ArrayList called exercises
private CategoryTypes categoryType;
private TangibleTypes tangibleType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_list);
LinearLayout relativeLayout = (LinearLayout) findViewById(R.id.exerciseLayout); //The layout used to put the buttons in
Intent intent = getIntent();
categoryType = CategoryTypes.valueOf(intent.getStringExtra("categoyType"));
tangibleType = TangibleTypes.valueOf(intent.getStringExtra("tangibleType"));
System.out.println("Category sent was: "+categoryType);
System.out.println("Tangible sent was: "+tangibleType);
//Contruction and putting the objects into the aforementioned Exercise Array
//TODO: Add this to the aforementioned method
/*for (int i = 0; i <= 200; i++)
{
list.add(new Exercise("Exercise "+i, CategoryTypes.MOBILITY, TangibleTypes.CHAIR, "Lav sværhedsgrad",R.string.flexChair,this));
}*/
//Add BALANCE exercises here
list.add(new Exercise("Øvelse 1",CategoryTypes.BALANCE, TangibleTypes.CHAIR,"Lav sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 5",CategoryTypes.BALANCE, TangibleTypes.TABLE,"Mellem sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 1",CategoryTypes.BALANCE, TangibleTypes.CHAIR,"Lav sværhedsgrad",R.string.flexChair,this));
//Add STRENGTH exercises here
list.add(new Exercise("Øvelse 2",CategoryTypes.STRENGTH, TangibleTypes.BAND,"Mellem sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 2",CategoryTypes.STRENGTH, TangibleTypes.BAND,"Mellem sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 2",CategoryTypes.STRENGTH, TangibleTypes.BAND,"Mellem sværhedsgrad",R.string.flexChair,this));
//Add Mobility exercises here
list.add(new Exercise("Øvelse 3",CategoryTypes.MOBILITY, TangibleTypes.NOTHING,"Høj sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 6",CategoryTypes.MOBILITY,TangibleTypes.CHAIR,"Lav sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 3",CategoryTypes.MOBILITY, TangibleTypes.NOTHING,"Høj sværhedsgrad",R.string.flexChair,this));
//Add CARDIO exercises here
list.add(new Exercise("Øvelse 4",CategoryTypes.CARDIO, TangibleTypes.TABLE,"Høj sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 4",CategoryTypes.CARDIO, TangibleTypes.TABLE,"Høj sværhedsgrad",R.string.flexChair,this));
list.add(new Exercise("Øvelse 4",CategoryTypes.CARDIO, TangibleTypes.TABLE,"Høj sværhedsgrad",R.string.flexChair,this));
exercises = filterExercises(categoryType,tangibleType);
//Creating the buttons depending on the size of the list
// and setting the names to the list names
for (int i = 0; i < exercises.size(); i++)
{
MainActivity.makeButton(this, this, exercises.get(i).getExerciseName(), buttons, exercises.get(i).getColor(), i);
}
//Adding buttons to the layout and deleting the "wrong" buttons
for (int i = 0; i < buttons.size(); i++)
{
newAddButtonToLayout(buttons.get(i), relativeLayout, this, i);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_exercise_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//CategoryTypes categories = CategoryTypes.values()[which];
private ArrayList<Exercise> filterExercises (CategoryTypes categoryType, TangibleTypes tangibleType)
{
for (Exercise exercise : this.list) {
System.out.println("exercise"+exercise.toString());
if (exercise.isCategoryType(categoryType) && exercise.isTangibleType(tangibleType)) {
System.out.println("match");
exercises.add(exercise);
}
else if (categoryType == CategoryTypes.ALL && tangibleType == TangibleTypes.ALL)
{
exercises.add(exercise);
}
else if (categoryType == CategoryTypes.ALL && exercise.isTangibleType(tangibleType))
{
exercises.add(exercise);
}
else if (exercise.isCategoryType(categoryType) && tangibleType == TangibleTypes.ALL)
{
exercises.add(exercise);
}
}
return exercises;
}
public void sendWithData(int index)
{
Intent sendToClass = new Intent (this, ExerciseView.class);
sendToClass.putExtra("exerciseTitle",buttons.get(index).getText());
sendToClass.putExtra("difficulty",exercises.get(index).getDifficulty());
sendToClass.putExtra("description",R.string.flexChair);
startActivity(sendToClass);
}
@Override
public void onClick(View view)
{
for (int i = 0; i < exercises.size(); i++) {
if (view.getId() == i) {
String buttonName = exercises.get(i).getExerciseName();
switch (buttonName) {
case "Øvelse 1":
sendWithData(i);
break;
case "Øvelse 2": sendWithData(i);
break;
case "Øvelse 3":
sendWithData(i);
break;
case "Øvelse 4": sendWithData(i);
break;
case "Øvelse 5":
sendWithData(i);
break;
case "Øvelse 6": sendWithData(i);
break;
}
}
}
}
public void newAddButtonToLayout (Button button, LinearLayout layout, Context context, int index)
{
int counter = 0;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.weight = 1.0f;
params.setMargins(0,20,0,20);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
ArrayList<LinearLayout> rows = new ArrayList<LinearLayout>();
for (int i = 0; i < buttons.size(); i++)
{
if (counter == buttons.get(i).getId())
{
LinearLayout row = new LinearLayout(context);
row.setId(1000 + i);
row.setLayoutParams(layoutParams);
button.setLayoutParams(params);
row.addView(button);
layout.addView(row);
counter += 2;
rows.add(row);
}
}
for (int i = 0; i < rows.size(); i++)
{
layout.addView(rows.get(i));
System.out.println("Button's parent is: "+button.getParent());
}
}
}
И статически ссылочные makeButtons
public static void makeButton (Context context, View.OnClickListener view, String buttonText, ArrayList<Button> buttons, int colour, int id)
{
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/RobotoSlab-Regular.ttf");
Typeface tfBold = Typeface.createFromAsset(context.getAssets(),"fonts/RobotoSlab-Bold.ttf");
Button button = new Button(context);
button.setText(buttonText);
button.setId(id);
button.setOnClickListener(view);
button.setBackgroundColor(colour);
button.setPadding(0, 20, 0, 20);
button.setTextSize(25);
button.setTypeface(tfBold);
buttons.add(button);
System.out.println(button.getId());
}
Как иметь 2 кнопки в представлении и добавьте, что для любого количества кнопок в кнопках ArrayList? Без использования ListView или Adapters?
(Примечание: Я пытался найти родитель кнопки, но это нуль)
вы добавляете ту же кнопку дважды ... (переборе '' buttons' внутри buttons's' итерации - вы даже понять код?) – Selvin