我正在try 使用Mainactivity.java创建约束布局,但我遇到了一些问题.我拿到了下面的yields .
约束布局与父级的大小不匹配.
我已经创建了两个类,一个是MainActivity.java
,另一个是MyConstraintLayout.Java
MyconstraintLayout.java
package com.example.checkbox;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
public class MyConstraintLayout extends ConstraintLayout {
public MyConstraintLayout(@NonNull Context context) {
super(context);
setId(generateViewId());
ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
setLayoutParams(layout);
setBackgroundColor(getResources().getColor(R.color.teal_200));
createWidgets(context);
}
void createWidgets(Context context){
ConstraintLayout.LayoutParams l1 = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Button b1 = new Button(context);
b1.setText("Button");
b1.setId(generateViewId());
addView(b1);
setLayoutParams(l1);
ConstraintLayout.LayoutParams l2 = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Button b2 = new Button(context);
b2.setText("Button");
b2.setId(generateViewId());
addView(b2);
setLayoutParams(l2);
l1.bottomToBottom = getId();
l1.topToTop = getId();
l1.endToEnd= getId();
l1.startToStart = getId();
l2.bottomToBottom = getId();
l2.topToBottom = b1.getId();
l2.endToEnd= getId();
l2.startToStart = getId();
}
}
MainActivity.java
package com.example.checkbox;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyConstraintLayout parent_layout = new MyConstraintLayout(this);
setContentView(parent_layout);
}
}
没有任何XML文件.
先谢谢你