Программно установить ограничения между несколькими одинаковыми представлениями - PullRequest
0 голосов
/ 20 мая 2019

У меня есть constraintLayout, который содержит несколько nodeView.nodeView - это линия ImageView, прикрепленная к левой стороне круга ImageView node

Теперь я хочу соединить вместе количество узлов X.Чтобы программно установить ограничения, вы используете R.id, но, поскольку я соединяю несколько одинаковых узлов вместе, и все они совместно используют один и тот же R.id, это не работает.Есть ли способ указать конкретное представление ImageView как ссылку для установки ограничения для другого ImageView?Я начинаю думать, что я подхожу к этому неправильно.Благодарю.

РЕДАКТИРОВАТЬ: Здесь остальная часть кода.

код узла

private void init(Context context, AttributeSet attrs, String description, boolean active, boolean base) {
        View inflatedView = inflate(context, R.layout.tracking_node, this);
        nodeLine = inflatedView.findViewById(R.id.imageNodeLine);
        nodeImage = inflatedView.findViewById(R.id.imageNode);
        nodeText = inflatedView.findViewById(R.id.textNode);

        nodeLine.setId(View.generateViewId());
        nodeImage.setId(View.generateViewId());

        nodeText.setText(description);
        if (active){
            nodeImage.setImageResource(R.drawable.circle_green);
            nodeLine.setImageResource(R.color.support_success);
        }else{
            nodeImage.setImageResource(R.drawable.circle_grey);
            nodeImage.setImageResource(R.color.grey);
        }

        //Remove left-side connecting line if base node
        if (base){
            nodeLine.getLayoutParams().width = 20;
            nodeLine.setImageResource(R.color.transparent);
        }
    }

    public int getNodeImageId(){
        return nodeImage.getId();
    }

    public int getNodeLineId(){
        return nodeLine.getId();
    }

constraintLayout code

private void init(Context context, AttributeSet attrs) {
        View inflatedView = inflate(context, R.layout.delivery_status_view, this);
        deliveryTrackerView = inflatedView.findViewById(R.id.linearLayoutDeliveryTracking);
        shippingDetailsButton = inflatedView.findViewById(R.id.btnShippingDetails);


        //steps[] is a string array that contains the content of each node
        DeliveryNodeView node = new DeliveryNodeView(context, attrs, steps[0], true, true);
        //Saves resource ID of last node image
        int pastNodeID = node.getNodeImageId();

        //Generates nodes
        for (int i = 1; i < steps.length; i++){

            boolean active = ((i + 1) / currentStep) <= 1;
            node = new DeliveryNodeView(context, attrs, steps[i], active, false);
            int nodeLineID = node.getNodeLineId();


            ConstraintSet constraintSet = new ConstraintSet();
            constraintSet.clone(deliveryTrackerView);


            deliveryTrackerView.addView(node);
            constraintSet.connect(nodeLineID, ConstraintSet.START, pastNodeID, ConstraintSet.END);
            pastNodeID = node.getNodeImageId();

        }

    }

1 Ответ

0 голосов
/ 21 мая 2019

Есть несколько проблем с вашим кодом.Вот некоторый пример кода, который создает цветной прямоугольный массив размером 5x5, который выглядит следующим образом:

enter image description here

Комментарии в коде обозначают ключевые шаги. activity_main.xml является просто пустым ConstraintLayout .

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConstraintLayout layout = findViewById(R.id.layout);
        int colorCounter = 0;
        int idToTop = ConstraintSet.PARENT_ID;
        int idToTopSide = ConstraintSet.TOP;
        for (int i = 0; i < 5; i++) {
            int idToLeft = ConstraintSet.PARENT_ID;
            int idToLeftSide = ConstraintSet.START;
            for (int j = 0; j < 5; j++) {
                View box = getBox(colorCounter++ % 2 == 0);
                // Add the view before getting the ConstraintSet.
                layout.addView(box);
                ConstraintSet cs = new ConstraintSet();
                cs.clone(layout);
                // Must constrain the view horizontally...
                cs.connect(box.getId(), ConstraintSet.START, idToLeft, idToLeftSide);
                //... and vertically.
                cs.connect(box.getId(), ConstraintSet.TOP, idToTop, idToTopSide);
                idToLeft = box.getId();
                idToLeftSide = ConstraintSet.END;
                // Apply the ConstraintSet to the layout.
                cs.applyTo(layout);
            }
            idToTop = idToLeft;
            idToTopSide = ConstraintSet.BOTTOM;
        }
    }

    private View getBox(boolean isRed) {
        View view = new View(this);
        view.setId(View.generateViewId());
        view.setBackgroundColor((isRed) ? Color.RED : Color.BLUE);
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(200, 200);
        view.setLayoutParams(lp);
        return view;
    }
}

Альтернативный код с тем жерезультат, который отделяет создание представления от создания ConstraintSet соединений.Это может быть немного более эффективным.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConstraintLayout layout = findViewById(R.id.layout);
        int colorCounter = 0;

        int[][] connections = new int[5][5];
        for (int row = 0; row < 5; row++) {
            for (int col = 0; col < 5; col++) {
                View box = getBox(colorCounter++ % 2 == 0);
                // Add the view before getting the ConstraintSet.
                layout.addView(box);
                connections[row][col] = box.getId();
            }
        }

        int idToTop = ConstraintSet.PARENT_ID;
        int idToTopSide = ConstraintSet.TOP;
        ConstraintSet cs = new ConstraintSet();
        cs.clone(layout);
        for (int i = 0; i < 5; i++) {
            cs.connect(connections[i][0], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
            cs.connect(connections[i][0], ConstraintSet.TOP, idToTop, idToTopSide);
            for (int j = 1; j < 5; j++) {
                // Must constrain the view horizontally...
                cs.connect(connections[i][j], ConstraintSet.START, connections[i][j - 1], ConstraintSet.END);
                //... and vertically.
                cs.connect(connections[i][j], ConstraintSet.TOP, idToTop, idToTopSide);
                // Apply the ConstraintSet to the layout.
            }
            idToTop = connections[i][0];
            idToTopSide = ConstraintSet.BOTTOM;
        }
        cs.applyTo(layout);
    }

    private View getBox(boolean isRed) {
        View view = new View(this);
        view.setId(View.generateViewId());
        view.setBackgroundColor((isRed) ? Color.RED : Color.BLUE);
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(200, 200);
        view.setLayoutParams(lp);
        return view;
    }
}
...