您的位置:首页 > 移动开发 > Android开发

解决setBackground与在xml设置android:background不一致的问题

2013-04-22 12:18 295 查看
          若在xml中有其他的layout 属性,会导致在代码中setBackground与android:background不一致的现象:

        例如:

        <RelativeLayout

     android:layout_width="fill_parent"

     android:layout_height="wrap_content" 

     android:paddingLeft="12dp"

     android:paddingRight="12dp"

     android:paddingTop="12dp"

     android:paddingBottom="4dp"

     android:id="@+id/background" 

     android:background="@drawable/card_article_top"

         >

       若在代码中设置背景,则忽略了padding的效果,导致内容"放大"了,解决办法为:

       public void setBackGround(int resourceId) {

        int bottom = mBackground.getPaddingBottom();

        int top = mBackground.getPaddingTop();

        int right = mBackground.getPaddingRight();

        int left = mBackground.getPaddingLeft();

        mBackground.setBackgroundResource(resourceId);

        mBackground.setPadding(left, top, right, bottom);

    }

       需要注意的是,需要先setBackground后,setPadding,否则无效~

       其他属性类似~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐