本文整合前面四篇的控件,再结合豆瓣读书的API,做了一个搜索书籍和查看书籍信息的Demo。
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:cardview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.loopj.android:android-async-http:1.4.7'
compile 'com.google.code.gson:gson:2.3'
compile 'com.afollestad:material-dialogs:0.7.6.0'
}
使用了RecyclerView和CardView进行布局。
RecyclerView参考文章: Material Design控件使用(一)
CardView参考文章: Material Design控件使用(三)
图片的显示,使用了glide,用法比较简单
Glide.with(holder.ivBook.getContext())
.load(book.getImage())
.fitCenter()
.into(holder.ivBook);
搜索按钮(FAB)点击后,使用material-dialogs显示dialog
new MaterialDialog.Builder(getActivity())
.title(R.string.search)
.input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
@Override
public void onInput(MaterialDialog dialog, CharSequence input) {
if (!TextUtils.isEmpty(input)) {
doSearch(input.toString());
}
}
}).show();
使用android-async-http发送HTTP请求,gson解析数据
public static void searchBooks(String name, final IBookResponse<List<Book>> response) {
RequestParams params = new RequestParams();
params.put("q", name);
params.put("start", 0);
params.put("end", 50);
client.get(getAbsoluteUrl("book/search"), params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
Gson gson = new Gson();
JSONObject json = new JSONObject(new String(responseBody));
JSONArray jaBooks = json.optJSONArray("books");
List<Book> books = gson.fromJson(jaBooks.toString(), new TypeToken<List<Book>>() {
}.getType());
response.onData(books);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
获取数据后,更新RecyclerView
private void doSearch(String keyword) {
mProgressBar.setVisibility(View.VISIBLE);
Book.searchBooks(keyword, new Book.IBookResponse<List<Book>>() {
@Override
public void onData(List<Book> books) {
mAdapter = new MyAdapter(getActivity(), books);
mRecyclerView.setAdapter(mAdapter);
mProgressBar.setVisibility(View.GONE);
}
});
}
使用AppBarLayout+ TabLayout+ViewPager显示书籍信息,
具体布局参考: Material Design控件使用(四)
菜单栏实现请参考: Material Design控件使用(二)
项目源码已发布到Github
APK下载地址: demo.apk
源码地址: MaterialDesignExample