TYC OneWeek

第一步 依赖
/* ButterKnife 依赖 */
implementation ‘com.jakewharton:butterknife:10.2.3’
annotationProcessor ‘com.jakewharton:butterknife-compiler:10.2.3’

/* OkHttp */
implementation("com.squareup.okhttp3:okhttp:4.8.1")
implementation'com.squareup.okhttp3:logging-interceptor:4.8.1'

/* RecycleView */
implementation 'com.android.support:recyclerview-v7:27.1.1'

/* Gson */
implementation 'com.google.code.gson:gson:2.8.6'

/* Fresco */
implementation 'com.facebook.fresco:fresco:2.3.0'

标题

/* EventBus */
implementation 'org.greenrobot:eventbus:3.2.0'

/* 二维码 */
implementation 'cn.yipianfengye.android:zxing-library:2.2'
在上面的
 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
第二步 分包 创建类
1.
**api包(
api类**( /* 搜索接口 */
public static final String SEARCH_URL = "http://172.17.8.100/small/commodity/v1/findCommodityByKeyword?page=1&count=10&keyword=%E6%89%8B%E6%9C%BA";
))
**2.
app包(SmallApp类)**(_
public class SmallApp extends Application {

@Override
public void onCreate() {
    super.onCreate();

    // 初始化Fresco
    Fresco.initialize(this);

    /* 初始化二维码 */
    ZXingLibrary.initDisplayOpinion(this);
}

)
3.
base包
BaseActivity类
public abstract class BaseActivity

extends AppCompatActivity {

private Unbinder bind;
protected P mPresenter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Activity创建 的声明周期方法

    setContentView(setView());

    // ButterKnif 的绑定
    bind = ButterKnife.bind(this);

    // 初始化p 绑定视图
    if (mPresenter == null) {
        mPresenter = createPresenter();
    }
    mPresenter.attachView(this);

    loadData();

}

/**
 * 加载数据
 */
protected abstract void loadData();

/**
 * 创建Presenter的方法,让子类实现
 * @return
 */
protected abstract P createPresenter();

/**
 * 子类初始化布局的方法
 * @return
 */
protected abstract int setView();

@Override
protected void onDestroy() {
    super.onDestroy();
    bind.unbind();
    mPresenter.detachView();
}

}
BasePresenter类
public abstract class BasePresenter {

protected M model;
//protected V view;
protected WeakReference view;

/**
 * 绑定View
 *
 * @param v
 */
public void attachView(V v) {
    // 用弱引用操作V
    view = new WeakReference<>(v);
    model = createModel();
}

/**
 * 创建Mode的方法
 *
 * @return
 */
protected abstract M createModel();


public V getView() {
    return view.get();
}

/**
 * 解绑View
 */
public void detachView() {
    if (view.get() != null) {
        view.clear();
        view = null;
    }
    if (model != null) {
        model = null;
    }
}

}
4.
event包
AddShopCart类
public class AddShopCart {

private String shopTitle;

public AddShopCart(String shopTitle) {
    this.shopTitle = shopTitle;
}

public String getShopTitle() {
    return shopTitle;
}

public void setShopTitle(String shopTitle) {
    this.shopTitle = shopTitle;
}

}
CreateQrCodeEvent类
public class CreateQrCodeEvent {

private String shopTitle;
private Bitmap shopBitmap;

public CreateQrCodeEvent(String shopTitle, Bitmap shopBitmap) {
    this.shopTitle = shopTitle;
    this.shopBitmap = shopBitmap;
}

public String getShopTitle() {
    return shopTitle;
}

public void setShopTitle(String shopTitle) {
    this.shopTitle = shopTitle;
}

public Bitmap getShopBitmap() {
    return shopBitmap;
}

public void setShopBitmap(Bitmap shopBitmap) {
    this.shopBitmap = shopBitmap;
}

}
5.
home包
adapter包
HomeAdapter类
public class HomeAdapter extends RecyclerView.Adapter {

List resultBeans;

public HomeAdapter(List resultBeans) {
    this.resultBeans = resultBeans;
}

@NonNull
@Override
public HomeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new HomeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false));
}

@Override
public void onBindViewHolder(@NonNull HomeViewHolder holder, int position) {
    holder.shopImage.setImageURI(resultBeans.get(position).getMasterPic());
    holder.tvShopName.setText(resultBeans.get(position).getCommodityName());
    holder.ivAddShopCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // 发送普通事件
            AddShopCart addShopCart = new AddShopCart(resultBeans.get(position).getCommodityName());
            EventBus.getDefault().post(addShopCart);
        }
    });
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // 发送粘性事件,到第二个页面生成二维码

            // 获取商品图片的Bitmap
            FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory().getMainFileCache().getResource(new SimpleCacheKey(resultBeans.get(position).getMasterPic()));
            Bitmap bitmap = BitmapFactory.decodeFile(resource.getFile().getPath());
            CreateQrCodeEvent createQrCodeEvent = new CreateQrCodeEvent(resultBeans.get(position).getCommodityName(), bitmap);

            EventBus.getDefault().postSticky(createQrCodeEvent);

            holder.itemView.getContext().startActivity(new Intent(holder.itemView.getContext(), QrCodeActivity.class));
        }
    });
}

@Override
public int getItemCount() {
    return resultBeans.size();
}

public static class HomeViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.shop_image)
    SimpleDraweeView shopImage;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.add_shop_cart)
    ImageView ivAddShopCart;


    public HomeViewHolder(@NonNull View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

  /*  @OnClick(R.id.add_shop_cart)
    public void onAddShopCart() {
        //System.out.println("点击添加");
        AddShopCart addShopCart = new AddShopCart();
    }*/
}

}
contract类
public interface HomeContract {

interface IHomeModel {
    // 从服务器获取数据的方法
    void getData(String url, OkHttpUtil.HttpCallBack callBack);
}

interface IHomeView {
    // 显示数据的方法
    void showData(String result);
}

interface IHomePresenter {
    // 请求数据的业务
    void getHomeData();
}
m包
**加粗样式**
bean包
HomeModelImpl类
public class HomeModelImpl implements HomeContract.IHomeModel {

@Override
public void getData(String url, OkHttpUtil.HttpCallBack callBack) {
    // 调用OkHttpUtils请求数据
    OkHttpUtil.getInstance().get(url, callBack);
}

}
p包
HomePresenterImpl类
public class HomePresenterImpl extends BasePresenter implements HomeContract.IHomePresenter {
@Override
public void getHomeData() {
model.getData(Api.SEARCH_URL, new OkHttpUtil.HttpCallBack() {
@Override
public void onSuccess(String result) {
getView().showData(result);
}

        @Override
        public void onFailure(String error) {

        }
    });
}

@Override
protected HomeContract.IHomeModel createModel() {
    return new HomeModelImpl();
}

}
v包
MainActivity类
public class MainActivity extends BaseActivity implements HomeContract.IHomeView {

@BindView(R.id.rv_home) RecyclerView rvHome;

@Override
protected void loadData() {
    mPresenter.getHomeData();
}

@Override
protected HomePresenterImpl createPresenter() {
    return new HomePresenterImpl();
}

@Override
protected int setView() {
    return R.layout.activity_main;
}

@Override
public void showData(String result) {
    Log.i("TAG", result);
    Gson gson = new Gson();
    HomeBean homeBean = gson.fromJson(result, HomeBean.class);
    /* 首页要展示的列表数据 */
    List resultBeans = homeBean.getResult();

    // 设置布局管理器
    rvHome.setLayoutManager(new LinearLayoutManager(this));
    // 设置适配器
    rvHome.setAdapter(new HomeAdapter(resultBeans));

}


@Subscribe(threadMode = ThreadMode.MAIN)
public void onAddShopCartEvent(AddShopCart addShopCart) {
    Toast.makeText(this, "添加" + addShopCart.getShopTitle() + "到购物车", Toast.LENGTH_SHORT).show();
}

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

}
加粗样式
qrcode包
QrCodeActivity类
public class QrCodeActivity extends AppCompatActivity {

@BindView(R.id.iv_qrcode)
ImageView imageView;
private Bitmap qrCodeBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qr_code);

    ButterKnife.bind(this);

    imageView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            MultiFormatReader multiFormatReader = new MultiFormatReader();

            // 解码的参数
            Hashtable hints = new Hashtable(2);
            // 可以解析的编码类型
            Vector decodeFormats = new Vector();
            if (decodeFormats == null || decodeFormats.isEmpty()) {
                decodeFormats = new Vector();

                // 这里设置可扫描的类型,我这里选择了都支持
                decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
                decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
                decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
            }
            hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
            // 设置继续的字符编码格式为UTF8
            // hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
            // 设置解析配置参数
            multiFormatReader.setHints(hints);

            // 开始对图像资源解码
            Result rawResult = null;
            try {
                rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(qrCodeBitmap))));
            } catch (Exception e) {
                e.printStackTrace();
            }

            Toast.makeText(QrCodeActivity.this, rawResult.getText(), Toast.LENGTH_SHORT).show();
            return true;
        }
    });
}

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onCreateQrCodeEvent(CreateQrCodeEvent createQrCodeEvent) {
    // 生成二维码
    //System.out.println(createQrCodeEvent.getShopTitle());
    qrCodeBitmap = CodeUtils.createImage(createQrCodeEvent.getShopTitle(), 500, 500, createQrCodeEvent.getShopBitmap());
    imageView.setImageBitmap(qrCodeBitmap);
}

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

}
util包
OkHttpUtil类
public class OkHttpUtil {

private OkHttpClient client;
private static OkHttpUtil util;

// 使用Handler把网络数据切换到主线程
private Handler mHandler;

private OkHttpUtil() {
    // 日志拦截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    // 通过Builder创建OkHttpClient
    client = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build();

    // 获取主线程的Handler
    mHandler = new Handler(Looper.getMainLooper());

    // 不添加拦截器
    // client = new OkHttpClient();
}

public static OkHttpUtil getInstance() {
    if (util == null) {
        util = new OkHttpUtil();
    }
    return util;
}


public void get(String url, HttpCallBack callback) {
    Request request = new Request.Builder()
            .url(url)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {

        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 通过Handler的post把数据发送到主线程
                    try {
                        callback.onSuccess(response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });
}



/**
 * 响应数据的接口回调
 */
public interface HttpCallBack {

    void onSuccess(String result);

    void onFailure(String error);
}

}
加粗样式
activity_main.xml布局

android:id="@+id/rv_home"
android:layout_width=“match_parent”
android:layout_height=“match_parent” />
加粗样式
activity_qr_code.xml布局


**加粗样式** home_item.xml布局





权限

注册信息

    


    -
    


        -
        

            

            

        

    


你可能感兴趣的:(java,android)