如何在ConstraintLayout的子Cas上使用ConstraintSet

时间:2018-12-28 20:18:31

标签: android constraints android-constraintlayout

我有一个继承ConstraintLayout的类,该类表示我以编程方式操作的活动的一部分。我有它的XML版本,似乎可以使用,并且我尝试以编程方式复制此代码。我在应用程序的各种活动中多次使用了此概念,因此认为将其自动化会很好。我建立了一个类作为ConstraintLayout的子类,并尝试向该类添加视图,当我尝试在addBusinessDay方法或生成活动中克隆它自己的ConstraintSet时,该活动将失败。

如果我尝试通过尝试的活动设置约束,则:

    ConstraintSet cs = new ConstraintSet();
    cs.clone(mBusinessWeek);
    cs.connect(mIds[0], ConstraintSet.START, mBusinessWeek.mId, ConstraintSet.START, 0);
    cs.setHorizontalBias(mIds[0], .5f);
    cs.connect(mIds[0], ConstraintSet.END, mIds[1], ConstraintSet.START, 8);
    cs.applyTo(mBusinessWeek);

我已将AddBusiness方法的签名修改为

public void addBusinessDay(String txt, int id, int sId, int eId){

并在方法末尾进行约束调用

    ConstraintSet cs = new ConstraintSet();
    cs.clone(this); // Even tried to comment this out
    cs.connect(id, ConstraintSet.START, sId, ConstraintSet.START, 0);
    cs.setHorizontalBias(id, .5f);
    cs.connect(id, ConstraintSet.END, eId, ConstraintSet.START, 8);
    cs.applyTo(this);

此错误在进行对clone(this)的调用时出现。如果我评论了在applyTo(this)上克隆活动故障的调用;

这是类和一个构造函数。

public class BusinessWeek extends ConstraintLayout {

    // My id
    public int mId;

    public BusinessWeek(Context c, ConstraintLayout parentLayout){
        super(c);
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        setLayoutParams(lp);

        mId = View.generateViewId();
        setId(mId);
        parentLayout.addView(this);
    }

    public void addBusinessDay(String txt, int id){
        TextView day = new TextView(getContext());
        ConstraintLayout.LayoutParams lp = new 
ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        day.setLayoutParams(lp);
        day.setText(txt);

        setId(id);
        addView(day);
    }
}

在我的活动中,我拨打了一组电话:

// Get the parent ConstraintLayout
ConstraintLayout cl = findViewById(R.id.clServiceDay);
// Instantiate class
mBusinessWeek = new BusinessWeek(this, cl);

// Generate ViewIds
int[7] mIds = new int[7];
for (int i = 0; i <7; i++)
    mIds[i] = = View.generateViewId();

// Generate businessDays in a horizontal chain
mBusinessWeek.addBusinessDay("Mo", mIds[0]);
mBusinessWeek.addBusinessDay("Tu", mIds[1]);
mBusinessWeek.addBusinessDay("We", mIds[2]);
mBusinessWeek.addBusinessDay("Th", mIds[3]);
mBusinessWeek.addBusinessDay("Fr", mIds[4]);
mBusinessWeek.addBusinessDay("Sa", mIds[5]);
mBusinessWeek.addBusinessDay("Su", mIds[6]);

这基本上可以正常工作,因为未设置约束集。正如人们所期望的那样,视图堆积在页面的左侧。

0 个答案:

没有答案