Search in sources :

Example 1 with IInnerImageSetter

use of com.tmall.wireless.tangram.util.IInnerImageSetter in project Tangram-Android by alibaba.

the class BannerTestActivity method onCreate.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        Picasso.setSingletonInstance(new Picasso.Builder(this).loggingEnabled(true).build());
    } catch (Exception e) {
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    recyclerView = (RecyclerView) findViewById(R.id.main_view);
    // Step 1: init tangram
    TangramBuilder.init(this, new IInnerImageSetter() {

        @Override
        public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view, @Nullable String url) {
            Picasso.with(BannerTestActivity.this).load(url).into(view);
        }
    }, ImageView.class);
    // Tangram.switchLog(true);
    mMainHandler = new Handler(getMainLooper());
    // Step 2: register build=in cells and cards
    builder = TangramBuilder.newInnerBuilder(this);
    // Step 3: register business cells and cards
    builder.registerCell(1, TestView.class);
    builder.registerCell(10, SimpleImgView.class);
    builder.registerCell(2, SimpleImgView.class);
    builder.registerCell(4, RatioTextView.class);
    builder.registerCell(110, TestViewHolderCell.class, new ViewHolderCreator<>(R.layout.item_holder, TestViewHolder.class, TextView.class));
    builder.registerCell(199, SingleImageView.class);
    builder.registerVirtualView("vvtest");
    // Step 4: new engine
    engine = builder.build();
    engine.setVirtualViewTemplate(VVTEST.BIN);
    engine.getService(VafContext.class).setImageLoaderAdapter(new IImageLoaderAdapter() {

        private List<ImageTarget> cache = new ArrayList<ImageTarget>();

        @Override
        public void bindImage(String uri, final ImageBase imageBase, int reqWidth, int reqHeight) {
            RequestCreator requestCreator = Picasso.with(BannerTestActivity.this).load(uri);
            Log.d("BannerTestActivity", "bindImage request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            ImageTarget imageTarget = new ImageTarget(imageBase);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }

        @Override
        public void getBitmap(String uri, int reqWidth, int reqHeight, final Listener lis) {
            RequestCreator requestCreator = Picasso.with(BannerTestActivity.this).load(uri);
            Log.d("BannerTestActivity", "getBitmap request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            ImageTarget imageTarget = new ImageTarget(lis);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }
    });
    Utils.setUedScreenWidth(720);
    // Step 5: add card load support if you have card that loading cells async
    engine.addCardLoadSupport(new CardLoadSupport(new AsyncLoader() {

        @Override
        public void loadData(Card card, @NonNull final LoadedCallback callback) {
            Log.w("Load Card", card.load);
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // do loading
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 10; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async loaded");
                            JSONObject style = new JSONObject();
                            style.put("bgColor", "#FF1111");
                            obj.put("style", style.toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // callback.fail(false);
                    callback.finish(engine.parseComponent(cells));
                }
            }, 200);
        }
    }, new AsyncPageLoader() {

        @Override
        public void loadData(final int page, @NonNull final Card card, @NonNull final LoadedCallback callback) {
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    Log.w("Load page", card.load + " page " + page);
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 9; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async page loaded, params: " + card.getParams().toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    List<BaseCell> cs = engine.parseComponent(cells);
                    if (card.page == 1) {
                        GroupBasicAdapter<Card, ?> adapter = engine.getGroupBasicAdapter();
                        card.setCells(cs);
                        adapter.refreshWithoutNotify();
                        Range<Integer> range = adapter.getCardRange(card);
                        adapter.notifyItemRemoved(range.getLower());
                        adapter.notifyItemRangeInserted(range.getLower(), cs.size());
                    } else
                        card.addCells(cs);
                    // mock load 6 pages
                    callback.finish(card.page != 6);
                    card.notifyDataChange();
                }
            }, 400);
        }
    }));
    engine.addSimpleClickSupport(new SampleClickSupport());
    // Step 6: enable auto load more if your page's data is lazy loaded
    engine.enableAutoLoadMore(true);
    // Step 7: bind recyclerView to engine
    engine.bindView(recyclerView);
    // Step 8: listener recyclerView onScroll event to trigger auto load more
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            engine.onScrolled();
        }
    });
    // Step 9: set an offset to fix card
    engine.getLayoutManager().setFixOffset(0, 40, 0, 0);
    // Step 10: get tangram data and pass it to engine
    String json = new String(getAssertsFile(this, "testdata.json"));
    JSONArray data = null;
    try {
        data = new JSONArray(json);
        engine.setData(data);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    findViewById(R.id.first).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            engine.refresh(true);
        }
    });
}
Also used : Listener(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.Listener) CardLoadSupport(com.tmall.wireless.tangram.support.async.CardLoadSupport) IInnerImageSetter(com.tmall.wireless.tangram.util.IInnerImageSetter) ArrayList(java.util.ArrayList) RequestCreator(com.squareup.picasso.RequestCreator) SampleClickSupport(com.tmall.wireless.tangram.example.support.SampleClickSupport) NonNull(android.support.annotation.NonNull) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) List(java.util.List) ArrayList(java.util.ArrayList) GroupBasicAdapter(com.tmall.wireless.tangram.core.adapter.GroupBasicAdapter) AsyncLoader(com.tmall.wireless.tangram.support.async.AsyncLoader) TestViewHolder(com.tmall.wireless.tangram.example.data.TestViewHolder) JSONArray(org.json.JSONArray) Handler(android.os.Handler) JSONException(org.json.JSONException) AsyncPageLoader(com.tmall.wireless.tangram.support.async.AsyncPageLoader) Range(com.alibaba.android.vlayout.Range) ImageView(android.widget.ImageView) SimpleImgView(com.tmall.wireless.tangram.example.data.SimpleImgView) SingleImageView(com.tmall.wireless.tangram.example.data.SingleImageView) View(android.view.View) TestView(com.tmall.wireless.tangram.example.data.TestView) TextView(android.widget.TextView) RecyclerView(android.support.v7.widget.RecyclerView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) JSONException(org.json.JSONException) IOException(java.io.IOException) Card(com.tmall.wireless.tangram.dataparser.concrete.Card) JSONObject(org.json.JSONObject) VafContext(com.tmall.wireless.vaf.framework.VafContext) IImageLoaderAdapter(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.IImageLoaderAdapter) Picasso(com.squareup.picasso.Picasso) RecyclerView(android.support.v7.widget.RecyclerView) ImageBase(com.tmall.wireless.vaf.virtualview.view.image.ImageBase) TargetApi(android.annotation.TargetApi)

Example 2 with IInnerImageSetter

use of com.tmall.wireless.tangram.util.IInnerImageSetter in project Tangram-Android by alibaba.

the class TangramActivity method onCreate.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    recyclerView = (RecyclerView) findViewById(R.id.main_view);
    // Step 1: init tangram
    TangramBuilder.init(this.getApplicationContext(), new IInnerImageSetter() {

        @Override
        public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view, @Nullable String url) {
            Picasso.with(TangramActivity.this.getApplicationContext()).load(url).into(view);
        }
    }, ImageView.class);
    // Tangram.switchLog(true);
    mMainHandler = new Handler(getMainLooper());
    // Step 2: register build=in cells and cards
    builder = TangramBuilder.newInnerBuilder(this);
    // Step 3: register business cells and cards
    builder.registerCell(1, TestView.class);
    builder.registerCell(10, SimpleImgView.class);
    builder.registerCell(2, SimpleImgView.class);
    builder.registerCell(4, RatioTextView.class);
    builder.registerCell(110, TestViewHolderCell.class, new ViewHolderCreator<>(R.layout.item_holder, TestViewHolder.class, TextView.class));
    builder.registerCell(199, SingleImageView.class);
    builder.registerVirtualView("vvtest");
    // Step 4: new engine
    engine = builder.build();
    engine.setVirtualViewTemplate(VVTEST.BIN);
    engine.setVirtualViewTemplate(DEBUG.BIN);
    engine.getService(VafContext.class).setImageLoaderAdapter(new IImageLoaderAdapter() {

        private List<ImageTarget> cache = new ArrayList<ImageTarget>();

        @Override
        public void bindImage(String uri, final ImageBase imageBase, int reqWidth, int reqHeight) {
            RequestCreator requestCreator = Picasso.with(TangramActivity.this).load(uri);
            Log.d("TangramActivity", "bindImage request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            ImageTarget imageTarget = new ImageTarget(imageBase);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }

        @Override
        public void getBitmap(String uri, int reqWidth, int reqHeight, final Listener lis) {
            RequestCreator requestCreator = Picasso.with(TangramActivity.this).load(uri);
            Log.d("TangramActivity", "getBitmap request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            ImageTarget imageTarget = new ImageTarget(lis);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }
    });
    Utils.setUedScreenWidth(720);
    // Step 5: add card load support if you have card that loading cells async
    engine.addCardLoadSupport(new CardLoadSupport(new AsyncLoader() {

        @Override
        public void loadData(Card card, @NonNull final LoadedCallback callback) {
            Log.w("Load Card", card.load);
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // do loading
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 10; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async loaded");
                            JSONObject style = new JSONObject();
                            style.put("bgColor", "#FF1111");
                            obj.put("style", style.toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // callback.fail(false);
                    callback.finish(engine.parseComponent(cells));
                }
            }, 200);
        }
    }, new AsyncPageLoader() {

        @Override
        public void loadData(final int page, @NonNull final Card card, @NonNull final LoadedCallback callback) {
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    Log.w("Load page", card.load + " page " + page);
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 9; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async page loaded, params: " + card.getParams().toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    List<BaseCell> cs = engine.parseComponent(cells);
                    if (card.page == 1) {
                        GroupBasicAdapter<Card, ?> adapter = engine.getGroupBasicAdapter();
                        card.setCells(cs);
                        adapter.refreshWithoutNotify();
                        Range<Integer> range = adapter.getCardRange(card);
                        adapter.notifyItemRemoved(range.getLower());
                        adapter.notifyItemRangeInserted(range.getLower(), cs.size());
                    } else
                        card.addCells(cs);
                    // mock load 6 pages
                    callback.finish(card.page != 6);
                    card.notifyDataChange();
                }
            }, 400);
        }
    }));
    engine.addSimpleClickSupport(new SampleClickSupport());
    // Step 6: enable auto load more if your page's data is lazy loaded
    engine.enableAutoLoadMore(true);
    engine.register(InternalErrorSupport.class, new SampleErrorSupport());
    // Step 7: bind recyclerView to engine
    engine.bindView(recyclerView);
    // Step 8: listener recyclerView onScroll event to trigger auto load more
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            engine.onScrolled();
        }
    });
    // Step 9: set an offset to fix card
    engine.getLayoutManager().setFixOffset(0, 40, 0, 0);
    // Step 10: get tangram data and pass it to engine
    String json = new String(getAssertsFile(this, "data.json"));
    JSONArray data = null;
    try {
        data = new JSONArray(json);
        engine.setData(data);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Also used : SampleErrorSupport(com.tmall.wireless.tangram.example.support.SampleErrorSupport) Listener(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.Listener) CardLoadSupport(com.tmall.wireless.tangram.support.async.CardLoadSupport) IInnerImageSetter(com.tmall.wireless.tangram.util.IInnerImageSetter) ArrayList(java.util.ArrayList) RequestCreator(com.squareup.picasso.RequestCreator) SampleClickSupport(com.tmall.wireless.tangram.example.support.SampleClickSupport) NonNull(android.support.annotation.NonNull) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) List(java.util.List) ArrayList(java.util.ArrayList) GroupBasicAdapter(com.tmall.wireless.tangram.core.adapter.GroupBasicAdapter) AsyncLoader(com.tmall.wireless.tangram.support.async.AsyncLoader) TestViewHolder(com.tmall.wireless.tangram.example.data.TestViewHolder) JSONArray(org.json.JSONArray) Handler(android.os.Handler) JSONException(org.json.JSONException) AsyncPageLoader(com.tmall.wireless.tangram.support.async.AsyncPageLoader) Range(com.alibaba.android.vlayout.Range) Card(com.tmall.wireless.tangram.dataparser.concrete.Card) JSONObject(org.json.JSONObject) VafContext(com.tmall.wireless.vaf.framework.VafContext) IImageLoaderAdapter(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.IImageLoaderAdapter) RecyclerView(android.support.v7.widget.RecyclerView) ImageBase(com.tmall.wireless.vaf.virtualview.view.image.ImageBase) TargetApi(android.annotation.TargetApi)

Example 3 with IInnerImageSetter

use of com.tmall.wireless.tangram.util.IInnerImageSetter in project Tangram-Android by alibaba.

the class RxTangramActivity method onCreate.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivityLFEventLifeCycleProvider.emitNext(ActivityLFEvent.CREATE);
    setContentView(R.layout.main_activity);
    recyclerView = (RecyclerView) findViewById(R.id.main_view);
    // Step 1: init tangram
    TangramBuilder.init(this.getApplicationContext(), new IInnerImageSetter() {

        @Override
        public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view, @Nullable String url) {
            Picasso.with(RxTangramActivity.this).load(url).into(view);
        }
    }, ImageView.class);
    // Tangram.switchLog(true);
    mMainHandler = new Handler(getMainLooper());
    // Step 2: register build=in cells and cards
    builder = TangramBuilder.newInnerBuilder(this);
    // Step 3: register business cells and cards
    builder.registerCell(1, TestView.class);
    builder.registerCell(10, SimpleImgView.class);
    builder.registerCell(2, SimpleImgView.class);
    builder.registerCell(4, RatioTextView.class);
    builder.registerCell(110, TestViewHolderCell.class, new ViewHolderCreator<>(R.layout.item_holder, TestViewHolder.class, TextView.class));
    builder.registerCell(199, SingleImageView.class);
    builder.registerVirtualView("vvtest");
    // Step 4: new engine
    engine = builder.build();
    engine.setSupportRx(true);
    engine.setVirtualViewTemplate(VVTEST.BIN);
    engine.getService(VafContext.class).setImageLoaderAdapter(new IImageLoaderAdapter() {

        private List<RxTangramActivity.ImageTarget> cache = new ArrayList<RxTangramActivity.ImageTarget>();

        @Override
        public void bindImage(String uri, final ImageBase imageBase, int reqWidth, int reqHeight) {
            RequestCreator requestCreator = Picasso.with(RxTangramActivity.this).load(uri);
            Log.d("TangramActivity", "bindImage request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            RxTangramActivity.ImageTarget imageTarget = new RxTangramActivity.ImageTarget(imageBase);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }

        @Override
        public void getBitmap(String uri, int reqWidth, int reqHeight, final Listener lis) {
            RequestCreator requestCreator = Picasso.with(RxTangramActivity.this).load(uri);
            Log.d("TangramActivity", "getBitmap request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            RxTangramActivity.ImageTarget imageTarget = new RxTangramActivity.ImageTarget(lis);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }
    });
    Utils.setUedScreenWidth(720);
    // Step 5: add card load support if you have card that loading cells async
    CardLoadSupport cardLoadSupport = new CardLoadSupport();
    engine.addCardLoadSupport(cardLoadSupport);
    Observable<Card> loadCardObservable = cardLoadSupport.observeCardLoading();
    Disposable dsp6 = loadCardObservable.observeOn(Schedulers.io()).map(new Function<Card, LoadGroupOp>() {

        @Override
        public LoadGroupOp apply(Card card) throws Exception {
            Log.d("TangramActivity", "loadCardObservable in map");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            JSONArray cells = new JSONArray();
            for (int i = 0; i < 10; i++) {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("type", 1);
                    obj.put("msg", "async loaded");
                    JSONObject style = new JSONObject();
                    style.put("bgColor", "#FF1111");
                    obj.put("style", style.toString());
                    cells.put(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            List<BaseCell> result = engine.parseComponent(cells);
            LoadGroupOp loadGroupOp = new LoadGroupOp(card, result);
            return loadGroupOp;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(cardLoadSupport.asDoLoadFinishConsumer());
    mCompositeDisposable.add(dsp6);
    Observable<Card> loadMoreObservable = cardLoadSupport.observeCardLoadingMore();
    Disposable dsp7 = loadMoreObservable.observeOn(Schedulers.io()).map(new Function<Card, LoadMoreOp>() {

        @Override
        public LoadMoreOp apply(Card card) throws Exception {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.w("TangramActivity", "loadMoreObservable " + card.load + " page " + card.page);
            JSONArray cells = new JSONArray();
            for (int i = 0; i < 9; i++) {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("type", 1);
                    obj.put("msg", "async page loaded, params: " + card.getParams().toString());
                    cells.put(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            List<BaseCell> cs = engine.parseComponent(cells);
            // mock loading 6 pages
            LoadMoreOp loadMoreOp = new LoadMoreOp(card, cs, card.page != 6);
            return loadMoreOp;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(cardLoadSupport.asDoLoadMoreFinishConsumer());
    mCompositeDisposable.add(dsp7);
    engine.addSimpleClickSupport(new SampleClickSupport());
    BannerSupport bannerSupport = new BannerSupport();
    engine.register(BannerSupport.class, bannerSupport);
    Disposable dsp1 = bannerSupport.observeSelected("banner1").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "1 selected " + integer);
        }
    });
    mCompositeDisposable.add(dsp1);
    final Disposable dsp2 = bannerSupport.observeSelected("banner1").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "2 selected " + integer);
        }
    });
    mCompositeDisposable.add(dsp2);
    Disposable dsp3 = bannerSupport.observeScrollStateChanged("banner2").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "state changed " + integer);
        }
    });
    mCompositeDisposable.add(dsp3);
    Disposable dsp4 = bannerSupport.observeScrolled("banner2").subscribe(new Consumer<ScrollEvent>() {

        @Override
        public void accept(ScrollEvent scrollEvent) throws Exception {
            Log.d("TangramActivity", "scrolled " + scrollEvent.toString());
        }
    });
    mCompositeDisposable.add(dsp4);
    // Step 6: enable auto load more if your page's data is lazy loaded
    engine.enableAutoLoadMore(true);
    // Step 7: bind recyclerView to engine
    engine.bindView(recyclerView);
    // Step 8: listener recyclerView onScroll event to trigger auto load more
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            engine.onScrolled();
        }
    });
    // Step 9: set an offset to fix card
    engine.getLayoutManager().setFixOffset(0, 40, 0, 0);
    // Step 10: get tangram data and pass it to engine
    // method 1, use simple consumer api
    // Observable.fromCallable(new Callable<byte[]>() {
    // @Override
    // public byte[] call() throws Exception {
    // Log.d("TangramActivity", "call asset in thread " + Thread.currentThread().getName());
    // 
    // return getAssertsFile(getApplicationContext(), "data.json");
    // }
    // }).subscribeOn(Schedulers.io())
    // .observeOn(Schedulers.computation())
    // .map(new Function<byte[], String>() {
    // @Override
    // public String apply(byte[] bytes) throws Exception {
    // Log.d("TangramActivity", "to string in thread " + Thread.currentThread().getName());
    // 
    // return new String(bytes);
    // }
    // }).map(new Function<String, JSONArray>() {
    // @Override
    // public JSONArray apply(String s) throws Exception {
    // Log.d("TangramActivity", "to json in thread " + Thread.currentThread().getName());
    // return new JSONArray(s);
    // }
    // }).observeOn(AndroidSchedulers.mainThread())
    // .doOnSubscribe(new Consumer<Disposable>() {
    // @Override
    // public void accept(Disposable disposable) throws Exception {
    // Log.d("TangramActivity", "do subscribe in thread " + Thread.currentThread().getName());
    // }
    // })
    // .subscribe(engine.asOriginalDataConsumer());
    // method 2, use transformer api
    // Observable.fromCallable(new Callable<byte[]>() {
    // @Override
    // public byte[] call() throws Exception {
    // Log.d("TangramActivity", "call asset in thread " + Thread.currentThread().getName());
    // 
    // return getAssertsFile(getApplicationContext(), "data.json");
    // }
    // }).map(new Function<byte[], String>() {
    // @Override
    // public String apply(byte[] bytes) throws Exception {
    // Log.d("TangramActivity", "to string in thread " + Thread.currentThread().getName());
    // 
    // return new String(bytes);
    // }
    // }).map(new Function<String, JSONArray>() {
    // @Override
    // public JSONArray apply(String s) throws Exception {
    // Log.d("TangramActivity", "to json in thread " + Thread.currentThread().getName());
    // return new JSONArray(s);
    // }
    // }).subscribeOn(Schedulers.io())
    // .compose(engine.getDataTransformer())
    // .doOnSubscribe(new Consumer<Disposable>() {
    // @Override
    // public void accept(Disposable disposable) throws Exception {
    // Log.d("TangramActivity", "do subscribe in thread " + Thread.currentThread().getName());
    // }
    // })
    // .subscribe(engine.asParsedDataConsumer());
    // method 3, emit json array and flat map to jsonobject
    Disposable dsp8 = Observable.create(new ObservableOnSubscribe<JSONArray>() {

        @Override
        public void subscribe(ObservableEmitter<JSONArray> emitter) throws Exception {
            String json = new String(getAssertsFile(getApplicationContext(), "data.json"));
            JSONArray data = null;
            try {
                data = new JSONArray(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            emitter.onNext(data);
            emitter.onComplete();
        }
    }).flatMap(new Function<JSONArray, ObservableSource<JSONObject>>() {

        @Override
        public ObservableSource<JSONObject> apply(JSONArray jsonArray) throws Exception {
            return JSONArrayObservable.fromJsonArray(jsonArray);
        }
    }).map(new Function<JSONObject, ParseSingleGroupOp>() {

        @Override
        public ParseSingleGroupOp apply(JSONObject jsonObject) throws Exception {
            return new ParseSingleGroupOp(jsonObject, engine);
        }
    }).compose(engine.getSingleGroupTransformer()).filter(new Predicate<Card>() {

        @Override
        public boolean test(Card card) throws Exception {
            return card.isValid();
        }
    }).map(new Function<Card, AppendGroupOp>() {

        @Override
        public AppendGroupOp apply(Card card) throws Exception {
            Thread.sleep(300);
            return new AppendGroupOp(card);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(engine.asAppendGroupConsumer(), new Consumer<Throwable>() {

        @Override
        public void accept(Throwable throwable) throws Exception {
            throwable.printStackTrace();
        }
    });
    mCompositeDisposable.add(dsp8);
    // method 4, create from json
    // Disposable dsp5 = Observable.create(new ObservableOnSubscribe<AppendGroupOp>() {
    // @Override
    // public void subscribe(ObservableEmitter<AppendGroupOp> emitter) throws Exception {
    // Log.d("TangramActivity", "subscribe in thread " + Thread.currentThread().getName());
    // String json = new String(getAssertsFile(getApplicationContext(), "data.json"));
    // JSONArray data = null;
    // try {
    // data = new JSONArray(json);
    // } catch (JSONException e) {
    // e.printStackTrace();
    // }
    // List<Card> cards = engine.parseData(data);
    // for (int i = 0, size = cards.size(); i < size; i++) {
    // emitter.onNext(new AppendGroupOp(cards.get(i)));
    // Log.d("TangramActivity", "emitter " + i);
    // try {
    // Thread.sleep(500);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // emitter.onComplete();
    // }
    // }).subscribeOn(Schedulers.io())
    // .observeOn(AndroidSchedulers.mainThread())
    // .doOnComplete(new Action() {
    // @Override
    // public void run() throws Exception {
    // final BaseCell cell = (BaseCell) engine.getGroupBasicAdapter().getComponents().get(1);
    // mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.last)).map(
    // new Function<Object, JSONObject>() {
    // @Override
    // public JSONObject apply(Object o) throws Exception {
    // cell.extras.put("title", "Rx标题2");
    // JSONObject jsonObject = cell.extras;
    // return jsonObject;
    // }
    // }).subscribe(cell.asUpdateConsumer()));
    // }
    // })
    // .subscribe(engine.asAppendGroupConsumer());
    // mCompositeDisposable.add(dsp5);
    mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.first)).map(new Function<Object, UpdateCellOp>() {

        @Override
        public UpdateCellOp apply(Object o) throws Exception {
            BaseCell cell = (BaseCell) engine.getGroupBasicAdapter().getComponents().get(0);
            cell.extras.put("title", "Rx标题1");
            return new UpdateCellOp(cell);
        }
    }).subscribe(engine.asUpdateCellConsumer()));
    mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.count)).subscribe(new Consumer<Object>() {

        @Override
        public void accept(Object o) throws Exception {
            dsp2.dispose();
        }
    }));
}
Also used : ArrayList(java.util.ArrayList) ParseSingleGroupOp(com.tmall.wireless.tangram.op.ParseSingleGroupOp) LoadGroupOp(com.tmall.wireless.tangram.op.LoadGroupOp) Consumer(io.reactivex.functions.Consumer) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) List(java.util.List) ArrayList(java.util.ArrayList) TestViewHolder(com.tmall.wireless.tangram.example.data.TestViewHolder) Handler(android.os.Handler) Card(com.tmall.wireless.tangram.dataparser.concrete.Card) UpdateCellOp(com.tmall.wireless.tangram.op.UpdateCellOp) JSONObject(org.json.JSONObject) ScrollEvent(com.tmall.wireless.tangram.support.RxBannerScrolledListener.ScrollEvent) BannerSupport(com.tmall.wireless.tangram.support.BannerSupport) JSONObject(org.json.JSONObject) ImageBase(com.tmall.wireless.vaf.virtualview.view.image.ImageBase) AppendGroupOp(com.tmall.wireless.tangram.op.AppendGroupOp) Listener(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.Listener) BaseCell(com.tmall.wireless.tangram.structure.BaseCell) CardLoadSupport(com.tmall.wireless.tangram.support.async.CardLoadSupport) IInnerImageSetter(com.tmall.wireless.tangram.util.IInnerImageSetter) LoadMoreOp(com.tmall.wireless.tangram.op.LoadMoreOp) RequestCreator(com.squareup.picasso.RequestCreator) SampleClickSupport(com.tmall.wireless.tangram.example.support.SampleClickSupport) Function(io.reactivex.functions.Function) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONException(org.json.JSONException) IOException(java.io.IOException) VafContext(com.tmall.wireless.vaf.framework.VafContext) IImageLoaderAdapter(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.IImageLoaderAdapter) RecyclerView(android.support.v7.widget.RecyclerView) TargetApi(android.annotation.TargetApi)

Example 4 with IInnerImageSetter

use of com.tmall.wireless.tangram.util.IInnerImageSetter in project Tangram-Android by alibaba.

the class TangramDataParserActivity method onCreate.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    recyclerView = (RecyclerView) findViewById(R.id.main_view);
    // Step 1: init tangram
    TangramBuilder.init(this, new IInnerImageSetter() {

        @Override
        public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view, @Nullable String url) {
            Picasso.with(TangramDataParserActivity.this).load(url).into(view);
        }
    }, ImageView.class);
    // Tangram.switchLog(true);
    mMainHandler = new Handler(getMainLooper());
    // Step 2: register build=in cells and cards
    builder = TangramBuilder.newInnerBuilder(this);
    // add: custom dataParser
    builder.setDataParser(new SampleDataParser());
    // Step 3: register business cells and cards
    builder.registerCard(1000, BannerCard.class);
    builder.registerCard(2000, FourColumnCard.class);
    builder.registerCell(1, TestView.class);
    builder.registerCell(10, SimpleImgView.class);
    builder.registerCell(2, SimpleImgView.class);
    builder.registerCell(4, RatioTextView.class);
    builder.registerCell(110, TestViewHolderCell.class, new ViewHolderCreator<>(R.layout.item_holder, TestViewHolder.class, TextView.class));
    builder.registerCell(199, SingleImageView.class);
    builder.registerVirtualView("vvtest");
    // Step 4: new engine
    engine = builder.build();
    engine.setVirtualViewTemplate(VVTEST.BIN);
    Utils.setUedScreenWidth(720);
    // Step 5: add card load support if you have card that loading cells async
    engine.addCardLoadSupport(new CardLoadSupport(new AsyncLoader() {

        @Override
        public void loadData(Card card, @NonNull final LoadedCallback callback) {
            Log.w("Load Card", card.load);
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // do loading
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 10; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async loaded");
                            JSONObject style = new JSONObject();
                            style.put("bgColor", "#FF1111");
                            obj.put("style", style.toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // callback.fail(false);
                    callback.finish(engine.parseComponent(cells));
                }
            }, 200);
        }
    }, new AsyncPageLoader() {

        @Override
        public void loadData(final int page, @NonNull final Card card, @NonNull final LoadedCallback callback) {
            mMainHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    Log.w("Load page", card.load + " page " + page);
                    JSONArray cells = new JSONArray();
                    for (int i = 0; i < 9; i++) {
                        try {
                            JSONObject obj = new JSONObject();
                            obj.put("type", 1);
                            obj.put("msg", "async page loaded, params: " + card.getParams().toString());
                            cells.put(obj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    List<BaseCell> cs = engine.parseComponent(cells);
                    if (card.page == 1) {
                        GroupBasicAdapter<Card, ?> adapter = engine.getGroupBasicAdapter();
                        card.setCells(cs);
                        adapter.refreshWithoutNotify();
                        Range<Integer> range = adapter.getCardRange(card);
                        adapter.notifyItemRemoved(range.getLower());
                        adapter.notifyItemRangeInserted(range.getLower(), cs.size());
                    } else
                        card.addCells(cs);
                    // mock load 6 pages
                    callback.finish(card.page != 6);
                    card.notifyDataChange();
                }
            }, 400);
        }
    }));
    engine.addSimpleClickSupport(new SampleClickSupport());
    // Step 6: enable auto load more if your page's data is lazy loaded
    engine.enableAutoLoadMore(true);
    // Step 7: bind recyclerView to engine
    engine.bindView(recyclerView);
    // Step 8: listener recyclerView onScroll event to trigger auto load more
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            engine.onScrolled();
        }
    });
    // Step 9: set an offset to fix card
    engine.getLayoutManager().setFixOffset(0, 40, 0, 0);
    // Step 10: get tangram data and pass it to engine
    String json = new String(getAssertsFile(this, "data_third.json"));
    JSONArray data = null;
    try {
        data = new JSONArray(json);
        engine.setData(data);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    findViewById(R.id.first).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            engine.refresh(true);
        }
    });
}
Also used : CardLoadSupport(com.tmall.wireless.tangram.support.async.CardLoadSupport) IInnerImageSetter(com.tmall.wireless.tangram.util.IInnerImageSetter) SampleClickSupport(com.tmall.wireless.tangram.example.support.SampleClickSupport) NonNull(android.support.annotation.NonNull) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) List(java.util.List) GroupBasicAdapter(com.tmall.wireless.tangram.core.adapter.GroupBasicAdapter) AsyncLoader(com.tmall.wireless.tangram.support.async.AsyncLoader) TestViewHolder(com.tmall.wireless.tangram.example.data.TestViewHolder) JSONArray(org.json.JSONArray) Handler(android.os.Handler) JSONException(org.json.JSONException) AsyncPageLoader(com.tmall.wireless.tangram.support.async.AsyncPageLoader) Range(com.alibaba.android.vlayout.Range) ImageView(android.widget.ImageView) SimpleImgView(com.tmall.wireless.tangram.example.data.SimpleImgView) SingleImageView(com.tmall.wireless.tangram.example.data.SingleImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TestView(com.tmall.wireless.tangram.example.data.TestView) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) BannerCard(com.tmall.wireless.tangram.structure.card.BannerCard) FourColumnCard(com.tmall.wireless.tangram.structure.card.FourColumnCard) Card(com.tmall.wireless.tangram.dataparser.concrete.Card) SampleDataParser(com.tmall.wireless.tangram.example.dataparser.SampleDataParser) JSONObject(org.json.JSONObject) RecyclerView(android.support.v7.widget.RecyclerView) TargetApi(android.annotation.TargetApi)

Aggregations

TargetApi (android.annotation.TargetApi)4 Handler (android.os.Handler)4 RecyclerView (android.support.v7.widget.RecyclerView)4 TextView (android.widget.TextView)4 Card (com.tmall.wireless.tangram.dataparser.concrete.Card)4 RatioTextView (com.tmall.wireless.tangram.example.data.RatioTextView)4 TestViewHolder (com.tmall.wireless.tangram.example.data.TestViewHolder)4 SampleClickSupport (com.tmall.wireless.tangram.example.support.SampleClickSupport)4 CardLoadSupport (com.tmall.wireless.tangram.support.async.CardLoadSupport)4 IInnerImageSetter (com.tmall.wireless.tangram.util.IInnerImageSetter)4 List (java.util.List)4 JSONArray (org.json.JSONArray)4 JSONException (org.json.JSONException)4 JSONObject (org.json.JSONObject)4 NonNull (android.support.annotation.NonNull)3 Range (com.alibaba.android.vlayout.Range)3 RequestCreator (com.squareup.picasso.RequestCreator)3 GroupBasicAdapter (com.tmall.wireless.tangram.core.adapter.GroupBasicAdapter)3 AsyncLoader (com.tmall.wireless.tangram.support.async.AsyncLoader)3 AsyncPageLoader (com.tmall.wireless.tangram.support.async.AsyncPageLoader)3