使用Java动态创建窗口小部件,不使用XML

时间:2017-12-10 11:42:28

标签: java android android-layout

我有这个布局

<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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="MyPackage.MainActivity"
    tools:showIn="@layout/app_bar_main"
    android:id="@+id/content_main">


    <TextProgress
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textprogress_day"
        android:background="@drawable/layout_border">
    </TextProgress>


</android.support.constraint.ConstraintLayout>

我想动态创建 TextProgerss (我的小部件) 没有xml

TextProgress类

   public class TextProgress extends ConstraintLayout {
        private TextView mTextView;
        private ProgressBar mProgressBar;

        public TextProgress(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            this.setBackgroundColor(Color.GREEN);

            initializeViews(context);
        }
.
.
.

我试过下面的代码

    ConstraintLayout cl= (ConstraintLayout) findViewById(R.id.content_main);
            TextProgress tp=new TextProgress(this,null);
            ConstraintLayout.LayoutParams tpParams=new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
            tp.setLayoutParams(tpParams);
            cl.addView(tp);

但是 MATCH_PARENT 无法正常工作

我不知道,如何在atrribute下动态创建

  

机器人:背景= “@绘制/ layout_border”

1 个答案:

答案 0 :(得分:0)

我能够解决部分问题。 MATCH_PARENT 问题解决了 看下面的代码

 ConstraintLayout cl= (ConstraintLayout) findViewById(R.id.content_main);
            TextProgress tp=new TextProgress(this,null);
            ConstraintLayout.LayoutParams tpParams=new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
            tp.setLayoutParams(tpParams);
            cl.addView(tp);

    ConstraintSet set = new ConstraintSet();

    set.constrainWidth(tp.getId(),ConstraintSet.MATCH_CONSTRAINT);
    set.constrainHeight(tp.getId(),ConstraintSet.WRAP_CONTENT);
    set.connect(tp.getId(), ConstraintSet.LEFT,
            ConstraintSet.PARENT_ID, ConstraintSet.LEFT);
    set.connect(tp.getId(), ConstraintSet.RIGHT,
            ConstraintSet.PARENT_ID, ConstraintSet.RIGHT);
        set.applyTo(cl);

边框问题已在here

中解决