微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JsonView beta1

根据json布局控件,适合控制 简易图墙 布局,支持控件嵌套,暂时支持内外边距,tro(toTheRightOf ,位于控件右边),tbo(toTheBottomOf,位于控件下面),背景颜色,图片,点击等,w指定占父布局宽度的比例,h指定自身高度与自身宽度的比例,id为控件设置id,tro和tbo后的数值为id,表明在对应控件右边或下边。具体支持属性如下。

public class SimpleView {
    public int  ml;
    public int  mr;
    public int  mt;
    public int  mb;
    public int  pl;
    public int  pt;
    public int  pr;
    public int  pb;
    public double  w;
    public double  h;
    public int  id;
    public String  bgColor;
    public String srcUrl;
    public String  click;
    public int tro;
    public int tbo;
}

json中,每一个[ ] 对应一个父布局,[ ] 中第一个元素为该父布局的属性(内外边距,背景等),其余元素每一个对应一个子控件。

json示例如下:

[
  {
    "ml":0,"mr":0,"mt":0,"mb":0,"pl":0,"pt":0,"pr":0,"pb":0,"w":0.99,"h":0.66,"bgColor":"#e1e1e1","bg":"http://...png....1","click":"xx://xx"
  },{
    "id":1,"ml":0,"w":0.66,"h":1,"bgColor":"#00ff00","srcUrl":"http://img2.3lian.com/2014/c7/12/d/77.jpg","click":"xx://xx"

  },{
    "id":2,"tro":1,"w":0.33,"h":0.5,"bgColor":"#0000ff","srcUrl":"http://pic3.bbzhi.com/fengjingbizhi/gaoqingkuanpingfengguangsheyingps/show_fengjingta_281299_11.jpg",{
    "id":3,"tbo":2,"bgColor":"#ffff00","srcUrl":"http://www.bz55.com/uploads1/allimg/120312/1_120312100435_8.jpg",{
    "id":4,"tbo":3,"w":0.17,"h":2,"bgColor":"#ff0000",{
    "id":5,"tro":4,"w":0.18,"click":"xx://xx"
  }
]
对应效果图如下:



关键代码如下:(需要使用imageloader加载图片和fastjson解析json)

package view.mogu.com.simplehtml;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wanjian on 2016/10/8.
 */

public class JsonView extends ViewGroup {
    public JsonView(Context context) {
        super(context);
    }

    public JsonView(Context context,AttributeSet attrs) {
        super(context,attrs);
    }

    public JsonView(Context context,AttributeSet attrs,int defStyleAttr) {
        super(context,attrs,defStyleAttr);
    }

    @SuppressLint("NewApi")
    public JsonView(Context context,int defStyleAttr,int defStyleRes) {
        super(context,defStyleAttr,defStyleRes);
    }

    @Override
    protected void onLayout(boolean changed,int l,int t,int r,int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view.getVisibility() == GONE) {
                continue;
            }

            int left = 0;
            int top = 0;
            LayoutParams param = ((LayoutParams) view.getLayoutParams());
            View leftView = findbrotherById(param.getToTheRightOf());
            if (leftView != null) {
                left = leftView.getRight() + ((LayoutParams) leftView.getLayoutParams()).rightMargin + param.leftMargin;
            }else{
                left=getPaddingLeft()+ param.leftMargin;
            }

            View topView = findbrotherById(param.getToTheBottomOf());
            if (topView != null) {
                top = topView.getBottom() + ((LayoutParams) topView.getLayoutParams()).bottomMargin + param.topMargin;
            }else{
                top=getPaddingTop()+param.topMargin;
            }
            view.layout(left,top,left+param.width,top+param.height);

        }
    }

    private View findbrotherById(int id) {
        if (id == 0) {
            return null;
        }
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view.getId() == id && id != 0) {
                return view;
            }
        }
        return null;
    }

    private ViewGroup.LayoutParams param;
    public void inflat(String simpleHtml,int width,ViewGroup.LayoutParams param) {
//        parent.generateLayoutParams(new )
        this.param=param;
        List<Object> viewgroup = JSON.parseArray(simpleHtml);
        innerInflat(viewgroup,width);
    }

    protected void innerInflat(List<Object> viewgroup,int width) {
        if (viewgroup == null || viewgroup.size() == 0) {
            return;
        }

        Object obj = viewgroup.get(0);
        if (obj instanceof JSONObject) {
            final SimpleView simpleView = parseJsonObject((JSONObject) obj);
            setPadding(simpleView.pl,simpleView.pt,simpleView.pr,simpleView.pb);
            if (param!=null){
                param.width= (int) (width*simpleView.w);
                param.height= (int) (param.width*simpleView.h);
                setLayoutParams(param);
            }
            initView(simpleView,JsonView.this);
        } else {
            return;
        }

        for (int i = 1; i < viewgroup.size(); i++) {
            Object o = viewgroup.get(i);
            if (o instanceof List) {
                List<Object> views = (List<Object>) o;
                if (views.size() > 0) {
                    Object child = views.get(0);
                    if (child instanceof JSONObject) {
                        SimpleView simpleView = parseJsonObject((JSONObject) child);
                        JsonView view = createViewGroup(simpleView,width);
                        addView(view);
                        view.innerInflat(views,(int) (width * simpleView.w));
                    }
                }
            } else if (o instanceof JSONObject) {
                View view = createChildView(parseJsonObject((JSONObject) o),width);

                addView(view);
            }
        }
    }

    private SimpleView parseJsonObject(JSONObject jsobj) {
        SimpleView simpleView=new SimpleView();
        Field []fs=SimpleView.class.getDeclaredFields();
        for (Field f : fs) {
            String name=f.getName();
            Object obj=jsobj.get(name);
            try {
                f.setAccessible(true);
                if (obj instanceof BigDecimal){
                    f.set(simpleView,((BigDecimal) obj).doubleValue());
                }else{
                    f.set(simpleView,obj);
                }
                f.setAccessible(false);
            } catch (Exception e) {

            }
        }


        return simpleView;
    }

    private View createChildView(SimpleView simpleView,int width) {
        View view = createView(simpleView);
        LayoutParams param = createLayoutParam(simpleView,width);
        view.setLayoutParams(param);
        view.setId(simpleView.id);
        view.setPadding(simpleView.pl,simpleView.pb);
        initView(simpleView,view);
        return view;

    }

    private void initView(final SimpleView simpleView,View view) {
        try {
            int color = Color.parseColor(simpleView.bgColor);
            view.setBackgroundColor(color);

        } catch (Exception e) {
        }
        if (!TextUtils.isEmpty(simpleView.click)) {
            view.setonClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getContext(),"click: "+simpleView.click,Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    protected View createView(SimpleView simpleView) {
        ImageView iv = new ImageView(getContext());
        try {
            iv.setBackgroundColor(Color.parseColor(simpleView.bgColor));
        } catch (Exception e) {
        }
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        ImageLoader.getInstance().displayImage(simpleView.srcUrl,iv);
        return iv;
    }

    private JsonView createViewGroup(SimpleView simpleView,int width) {
        JsonView jsonView = new JsonView(getContext());
        LayoutParams param = createLayoutParam(simpleView,width);
        jsonView.setLayoutParams(param);
        jsonView.setId(simpleView.id);
        return jsonView;
    }

    @NonNull
    private LayoutParams createLayoutParam(SimpleView simpleView,int width) {
        LayoutParams param = new LayoutParams( (int)(width * simpleView.w),(int)(width * simpleView.w * simpleView.h));
        param.setMargins(simpleView.ml,simpleView.mt,simpleView.mr,simpleView.mb);
        param.setToTheRightOf(simpleView.tro);
        param.setToTheBottomOf(simpleView.tbo);
        return param;
    }

    class LayoutParams extends MarginLayoutParams {

        public LayoutParams(Context c,AttributeSet attrs) {
            super(c,attrs);
        }

        public LayoutParams(int width,int height) {
            super(width,height);
        }

        public LayoutParams(MarginLayoutParams source) {
            super(source);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }

        int toTheRightOf;
        int toTheBottomOf;

        public void setToTheRightOf(int toTheRightOf) {
            this.toTheRightOf = toTheRightOf;
        }

        public void setToTheBottomOf(int toTheBottomOf) {
            this.toTheBottomOf = toTheBottomOf;
        }

        public int getToTheRightOf() {
            return toTheRightOf;
        }

        public int getToTheBottomOf() {
            return toTheBottomOf;
        }
    }

}


package view.mogu.com.simplehtml;

/**
 * Created by wanjian on 2016/10/8.
 */

public class SimpleView {
    public int  ml;
    public int  mr;
    public int  mt;
    public int  mb;
    public int  pl;
    public int  pt;
    public int  pr;
    public int  pb;
    public double  w;
    public double  h;
    public int  id;
    public String  bgColor;
    public String srcUrl;
    public String  click;
    public int tro;
    public int tbo;
}

使用姿势:(json文件放在assets文件夹中)
package view.mogu.com.simplehtml;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(configuration);

        JsonView htmlView=new JsonView(MainActivity.this);

        try {
            InputStream inputStream=getAssets().open("layout3.json");
            byte[]b=new byte[inputStream.available()];
            inputStream.read(b);
            htmlView.inflat(new String(b),getResources().getdisplayMetrics().widthPixels,new FrameLayout.LayoutParams(0,0));
        } catch (IOException e) {
            e.printstacktrace();
        }
        setContentView(htmlView);
    }
}



附 几个json对应的布局
[
  {
    "ml":0,"mt":5,"mb":5,"w":1,"h":1.5,"mt":10,"w":0.5,"ml":5,"w":0.25,"tro":2,"mb":10,[
    {
      "ml":0,"bgColor":"#00ffff","srcUrl":"http://img3.iqilu.com/data/attachment/forum/201308/21/192654ai88zf6zaa60zddo.jpg","click":"xx://xx"
    },{
      "id":1,"bgColor":"#ffffff","click":"xx://xx"

    },{
      "id":2,"bgColor":"#000000","srcUrl":"http://h.hiphotos.baidu.com/image/h%3D200/sign=fc55a740f303918fc8d13aca613c264b/9213b07eca80653893a554b393dda144ac3482c7.jpg",{
      "id":3,"click":"xx://xx"

    }

  ]

]



[
  {
    "ml":0,"tro":0,"tbo":1,{
    "id":6,"tro":5,"click":"xx://xx"
  }


]



[
  {
    "ml":0,"tbo":0,"tro":3,"tbo":4,"click":"xx://xx"
  }


]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐