BlueLite
BlueLite

Reputation: 321

How do I get a ConstraintLayout from a View?

I have an app and I have a dynamically changing crosshair that is supposed to follow where the user clicks. What I'm trying to do to get the crosshair to move is changing the constraints on the crosshair relative to the sides of the view.

Here is my code.

ConstraintSet set = new ConstraintSet();
View layout = findViewById(R.id.crosshair);

set.clone((ConstraintLayout) layout);
set.clear(R.id.crosshair,ConstraintSet.LEFT);
set.clear(R.id.crosshair,ConstraintSet.TOP);
set.connect(R.id.crosshair,ConstraintSet.TOP,R.id.CourseMain,y);
set.connect(R.id.crosshair,ConstraintSet.LEFT,R.id.CourseMain,x);

set.applyTo((ConstraintLayout) layout);

Unfortunately, I can't cast a view to a constraint and I'm having problems finding how to get a constraint layout.

So, what I'm really asking is. How to I get a ConstraintLayout from a view OR how do I get a ConstraintLayout in general. I'm kinda lost there too.

Upvotes: 0

Views: 5049

Answers (2)

Paulami Biswas
Paulami Biswas

Reputation: 173

If you are using java declare a activity_main in res/layout folder:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/constraintLayoutParent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

</android.support.constraint.ConstraintLayout>

In this file the id given to the constraint layout is constraintLayoutParent

Declare an activity MainActivity.class:

import android.app.Activity;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        final ConstraintLayout mConstraintLayout=findViewById(R.id.constraintLayoutParent);

        mConstraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Constraint layout clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

In MainActivity.class the line:

final ConstraintLayout mConstraintLayout=findViewById(R.id.constraintLayoutParent);

Here the id should be same that is used in XML i.e constraintLayoutParent

Upvotes: 2

silvia.espinoza
silvia.espinoza

Reputation: 1

Your ConstraintLayout should have an id value, you could use that:

ConstraintLayout layout = (ConstraintLayout) this.findViewById(R.id.thelayoutid)

Upvotes: 0

Related Questions