最近根据Gank.io 参照着GankClient-Kotlin 写一个小项目GankClient总结一下技术,这里暂时使用java编写,运用到了:
- ButterKnife(黄油刀)xml视图依赖注入,简化findViewById()手工繁琐代码;
- Retrofit2+OkHttp3+RxJava2构建当前流行的网络框架;
- Glide图片加载库,减少图片OOM问题;
- MVP架构 分离Activity的model层功能,只作为view层,增加presenter层构建连接;
- Dagger2对mvp架构使用依赖注入 ,进行进一步隔离model层,view层, presenter层;
- 下面介绍一下各部分用法
ButterKnife
JakeWharton大神的https://github.com/JakeWharton/butterknife
在model的builde.gradle
dependencies {
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
在Acitivty中使用
选中activity_detail,按alt+Insert,即可看到Butterknife插件
结果如下
DetailActivity
public class DetailActivity extends AppCompatActivity {
@BindView(R.id.wv_detail)
WebView wvDetail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
```
}
activity_detail.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wega.gankclient.home.detail.DetailActivity">
<WebView
android:id="@+id/wv_detail"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="0dp"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
在Fragment使用
插件步骤与在Acitivty一致,结果有些不同
BaseListFragment
public class BaseListFragment<T> extends Fragment
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout mSwipeRefreshLayout;
Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mLayout = inflater.inflate(setLayout(), container, false);
unbinder = ButterKnife.bind(this, mLayout);
return mLayout;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
fragment_base_list.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>