【问题标题】:Dynamic add custome view and set it's property android动态添加自定义视图并设置其属性android
【发布时间】:2014-10-28 14:34:44
【问题描述】:

我添加了SingleFingerView,这是自定义视图

它的xml属性是

<com.example.testimg.SingleFingerView
        android:id="@+id/tiv"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        pushtouch:centerInParent="true"
        pushtouch:image="@drawable/crown"
        pushtouch:image_height="150dp"
        pushtouch:image_width="200dp"
        pushtouch:push_image="@drawable/push_btn"
        pushtouch:push_image_height="50dp"
        pushtouch:push_image_width="50dp" />

但是我已经通过 Java 添加了这个自定义视图

LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.MATCH_PARENT);
                SingleFingerView btn = new SingleFingerView(MyActivity.this);
                btn.setLayoutParams(lparams);

但我不知道如何通过 java 设置它的 pushtouch 属性

     pushtouch:centerInParent="true"
        pushtouch:image="@drawable/crown"
        pushtouch:image_height="150dp"
        pushtouch:image_width="200dp"
        pushtouch:push_image="@drawable/push_btn"
        pushtouch:push_image_height="50dp"
        pushtouch:push_image_width="50dp" 

谁能帮帮我

【问题讨论】:

    标签: android android-custom-view


    【解决方案1】:

    您应该为 SingleFingerView 中的每个属性创建公共方法,例如:

    public void setCenterInParent(boolean centerInParent) {
        this.mCenterInParent = centerInParent;
    }
    
    public void setImageDrawable(Drawable d) {
        this.mImageDrawable = d;
    }
    
    public void setImageHeight(int height) {
        this.mImageHeight = height * _1dp;
    }
    

    然后在您的活动/片段中:

    LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.MATCH_PARENT);
    SingleFingerView btn = new SingleFingerView(MyActivity.this);
    btn.setLayoutParams(lparams);
    btn.setCenterInParent(true);
    btn.setImageDrawable(getResources().getDrawable(R.drawable.crown));
    btn.setImageHeight(200);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多