基于Material Design和MVP的新闻客户端
Screenshot
新闻列表
图片
...
项目结构:
项目中涉及到
DrawerLayout
ActionBarDrawerToggle
Toolbar
NavigationView
AppBarLayout TabLayout
Snackbar代替Toast
Activity转场过渡动画
Glide
OkHttp网络连接封装
说明:
- MainActivity中把整个DrawerLayout作为根View添加到 DecorView的 id为android.R.id.content 的View中。 DrawerLayout内部对上滑做了处理,所以我们在上滑RecyclerView会隐藏Toolbar部分。
2.添加如新闻列表的Tab(TabLayout)
头条 NBA 汽车 笑话
代码层
mTablayout = (TabLayout) view.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
//设置OffscreenPageLimit 我们可以设置 缓存view 的个数。
mViewPager.setOffscreenPageLimit(3);
setupViewPager(mViewPager);
mTablayout.addTab(mTablayout.newTab().setText(R.string.top));
mTablayout.addTab(mTablayout.newTab().setText(R.string.nba));
mTablayout.addTab(mTablayout.newTab().setText(R.string.cars));
mTablayout.addTab(mTablayout.newTab().setText(R.string.jokes));
//ViewPage 的OnPageChangeListener 是在这个步骤中设定的
mTablayout.setupWithViewPager(mViewPager);
private void setupViewPager(ViewPager mViewPager) {
//Fragment中嵌套使用Fragment一定要使用getChildFragmentManager(),否则会有问题
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
adapter.addFragment(NewsListFragment.newInstance(NEWS_TYPE_TOP), getString(R.string.top));
adapter.addFragment(NewsListFragment.newInstance(NEWS_TYPE_NBA), getString(R.string.nba));
adapter.addFragment(NewsListFragment.newInstance(NEWS_TYPE_CARS), getString(R.string.cars));
adapter.addFragment(NewsListFragment.newInstance(NEWS_TYPE_JOKES), getString(R.string.jokes));
mViewPager.setAdapter(adapter);
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private final List mFragments = new ArrayList<>();
private final List mFragmentTitles = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
public class NewsListFragment extends Fragment implements NewsView, SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "NewsListFragment";
private SwipeRefreshLayout mSwipeRefreshWidget;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private NewsAdapter mAdapter;
private List mData;
private NewsPresenter mNewsPresenter;
private int mType = NewsFragment.NEWS_TYPE_TOP;
private int pageIndex = 0;
public static NewsListFragment newInstance(int type) {
Bundle args = new Bundle();
NewsListFragment fragment = new NewsListFragment();
args.putInt("type", type);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNewsPresenter = new NewsPresenterImpl(this);
mType = getArguments().getInt("type");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newslist, null);
mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
mSwipeRefreshWidget.setColorSchemeResources(R.color.primary,
R.color.primary_dark, R.color.primary_light,
R.color.accent);
mSwipeRefreshWidget.setOnRefreshListener(this);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new NewsAdapter(getActivity().getApplicationContext());
mAdapter.setOnItemClickListener(mOnItemClickListener);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnScrollListener(mOnScrollListener);
onRefresh();
return view;
}
private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
private int lastVisibleItem;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE
&& lastVisibleItem + 1 == mAdapter.getItemCount()
&& mAdapter.isShowFooter()) {
//加载更多
LogUtils.d(TAG, "loading more data");
mNewsPresenter.loadNews(mType, pageIndex);
}
}
};
private NewsAdapter.OnItemClickListener mOnItemClickListener = new NewsAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
NewsBean news = mAdapter.getItem(position);
Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
intent.putExtra("news", news);
View transitionView = view.findViewById(R.id.ivNews);
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
transitionView, getString(R.string.transition_news_img));
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
}
};
@Override
public void showProgress() {
mSwipeRefreshWidget.setRefreshing(true);
}
@Override
public void addNews(List newsList) {
mAdapter.isShowFooter(true);
if(mData == null) {
mData = new ArrayList();
}
mData.addAll(newsList);
if(pageIndex == 0) {
mAdapter.setmDate(mData);
} else {
//如果没有更多数据了,则隐藏footer布局
if(newsList == null || newsList.size() == 0) {
mAdapter.isShowFooter(false);
}
mAdapter.notifyDataSetChanged();
}
pageIndex += Urls.PAZE_SIZE;
}
@Override
public void hideProgress() {
mSwipeRefreshWidget.setRefreshing(false);
}
@Override
public void showLoadFailMsg() {
if(pageIndex == 0) {
mAdapter.isShowFooter(false);
mAdapter.notifyDataSetChanged();
}
View view = getActivity() == null ? mRecyclerView.getRootView() : getActivity().findViewById(R.id.drawer_layout);
Snackbar.make(view, getString(R.string.load_fail), Snackbar.LENGTH_SHORT).show();
}
@Override
public void onRefresh() {
pageIndex = 0;
if(mData != null) {
mData.clear();
}
mNewsPresenter.loadNews(mType, pageIndex);
}
}
3.Activity转场过渡动画
效果如图
实现:
private NewsAdapter.OnItemClickListener mOnItemClickListener = new NewsAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
NewsBean news = mAdapter.getItem(position);
Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
intent.putExtra("news", news);
View transitionView = view.findViewById(R.id.ivNews);
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
transitionView, getString(R.string.transition_news_img));
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
}
};
getString(R.string.transition_news_img))到底是什么呢?其实他就是要启动Activity的ImageView的id,如下:
4.Snackbar代替Toast
好处在于可以用于交互了。
注意FloatingActionButton的效果
代码:
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Snackbar.make(view, "Snackbar可以左滑取消哦~", Snackbar.LENGTH_LONG)
.setAction("Action", new View.OnClickListener() {
@Override
public void onClick(View v) {
//点击Action弹出ActionClick的Snackbar
Snackbar.make(view,"ActionClick",Snackbar.LENGTH_LONG).show();
}
})
.setActionTextColor(getResources().getColor(android.R.color.holo_blue_bright))
.show();
}
});
4.图片加载Glide,用法类似于Picasso
工具类
public class ImageLoaderUtils {
public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
if(imageView == null) {
throw new IllegalArgumentException("argument error");
}
Glide.with(context).load(url).placeholder(placeholder)
.error(error).crossFade().into(imageView);
}
public static void display(Context context, ImageView imageView, String url) {
if(imageView == null) {
throw new IllegalArgumentException("argument error");
}
Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
.error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
}
}
5.OkHttp网络连接封装
先看使用:
@Override
public void loadNews(String url, final int type, final OnLoadNewsListListener listener) {
OkHttpUtils.ResultCallback loadNewsCallback = new OkHttpUtils.ResultCallback() {
@Override
public void onSuccess(String response) {
List newsBeanList = NewsJsonUtils.readJsonNewsBeans(response, getID(type));
listener.onSuccess(newsBeanList);
}
@Override
public void onFailure(Exception e) {
listener.onFailure("load news list failure.", e);
}
};
OkHttpUtils.get(url, loadNewsCallback);
}
调用,其中NewsPresenterImpl实现了NewsModelImpl.OnLoadNewsListListener接口
mNewsModel.loadNews(url, type, this);
篇幅原因,完整的工具类代码可以到github上查看。
项目地址:
https://github.com/jacky1234/SimpleNews