我可以使用ConstraintSet在ConstraintLayout中编程修改视图的约束条件,但在应用修改之前,我希望测试它是否已经完成。为此,我需要以编程方式访问ConstraintLayout中视图的当前约束条件。
例如,在这里,我想要删除TextView“title”顶部与TextView“subtitle”底部之间的约束条件。然后将TextView“title”的顶部限制为“videoView”的底部。但首先,我需要检查TextView“title”是否已经受到“videoView”的底部约束条件的限制(代码修改自android官方网站)。请注意,我无法在此网站上插入HTML的最后一行,它是用尖括号括起来的/android.support.constraint.ConstraintLayout。
例如,在这里,我想要删除TextView“title”顶部与TextView“subtitle”底部之间的约束条件。然后将TextView“title”的顶部限制为“videoView”的底部。但首先,我需要检查TextView“title”是否已经受到“videoView”的底部约束条件的限制(代码修改自android官方网站)。请注意,我无法在此网站上插入HTML的最后一行,它是用尖括号括起来的/android.support.constraint.ConstraintLayout。
public class MainActivity extends AppCompatActivity {
ConstraintSet mConstraintSet = new ConstraintSet(); // create a Constraint Set
ConstraintLayout mConstraintLayout; // cache the ConstraintLayout
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConstraintLayout = (ConstraintLayout) findViewById(R.id.root);
mConstraintSet.clone(mConstraintLayout); // get constraints from ConstraintSet
}
public void userDoesSomething(View v) {
//test if title has already been constrained to bottom of videoView
if (mConstraintLayout 'TITLE' IS NOT CONSTRAINED TO THE BOTTOM OF 'VIDEOVIEW'){
mConstraintSet.connect(R.id.Title, ConstraintSet.TOP, R.id.videoView, ConstraintSet.BOTTOM); // set new constraints to ConstraintSet
mConstraintSet.applyTo(mConstraintLayout); // set new constraints to ConstraintLayout
}
}
}
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.MainActivity"
android:orientation="vertical">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
android:id="@+id/subtitiles"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/videoView"
app:layout_constraintLeft_toLeftOf="parent"
android:gravity="center"
android:text="The problem with this pond is that there are too many toads"
android:textSize="25sp"
android:background="@android:color/white"
/>
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/subtitiles"
app:layout_constraintLeft_toLeftOf="parent"
android:gravity="center"
android:text="Toad"
android:textSize="25sp"
android:background="@android:color/white"
/>