涉及到的知识点有
1.自定义控件,重写控件的相关方法
实现:
(1)频道管理(带拖拽,动画)Android 高仿 频道管理----网易、今日头条、腾讯视频 (可以拖动的GridView)附源码DEMO
(2) 新闻列表中每个字段按照时间进行排列,并且带有悬浮效果
(3)城市选择列表中的城市信息按照首字母进行排列,并且带有悬浮效果
注意:(1)通过重写GridView。(2)和(3)通过重写ListView,之后通过接口判断是否在最最上方了,进行状态变更,DEMO的代码中可以清晰看懂
2.SQLITE数据库的使用
实现:保存用户设置的频道信息
3.Activity之间的动画跳转方式
4.Animation动画类的相关知识
实现:频道管理中频道的移动动画
5.WebView的相关知识和 jsoup库解析HTML
实现:新闻详情的查看、排版,图片信息的提取。(这块没深入研究,知识从别人那边借鉴了点放进去的)
6.重写ViewPager和ImageView
实现:图片浏览和通过手势放大缩小
7.GestureDetector手势类及OnGestureListener手势监听类的使用
实现:新闻详情页面根据手势滑动来关闭该页面
------------------------------主Activity就是一张图片几秒后跳转
public class MainActivity extends AppCompatActivity { private TextView text_view; private Button button_tiyan; int time = 3; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0){ if (time > 0){ time --; text_view.setText(time + "秒后进入"); handler.sendEmptyMessageDelayed(0 , 1000); }else{ Intent intent = new Intent(MainActivity.this , SecondActivity.class); startActivity(intent); finish(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text_view = (TextView) findViewById(R.id.text_view); button_tiyan = (Button) findViewById(R.id.button_tiyan);
//点击按钮跳转 button_tiyan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this , SecondActivity.class); startActivity(intent); finish(); } });
//发送 handler.sendEmptyMessageDelayed(0 , 1000); } @Override protected void onPause() { super.onPause(); handler.removeMessages(0); } }------------------------------第二个Activity主要是fragment之间的切换(点击按钮,fragment切换,没有滑动的效果注意)
布局这个radio_group按钮,(这里的按钮是图片)改变背景的xml
public class SecondActivity extends AppCompatActivity { private RadioGroup group; private List-------------------------------------------------------------------------------第一个fragment,也是首页list = new ArrayList<>(); private FragmentManager manager; private Fragment_shou fragment_shou; private Fragment_two fragment_two; private Fragment_my fragment_my; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); group = (RadioGroup) findViewById(R.id.radio_group); manager = getSupportFragmentManager(); fragment_shou = new Fragment_shou(); manager.beginTransaction().add(R.id.fragme_layout , fragment_shou).commit(); group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { FragmentTransaction transaction = manager.beginTransaction(); if (fragment_shou != null){ transaction.hide(fragment_shou); } if (fragment_two != null){ transaction.hide(fragment_two); } if (fragment_my != null){ transaction.hide(fragment_my); } switch (i){ case R.id.button_01: if (fragment_shou == null){ fragment_shou = new Fragment_shou(); transaction.add(R.id.fragme_layout , fragment_shou); }else{ transaction.show(fragment_shou); } break; case R.id.button_02: if (fragment_two == null){ fragment_two = new Fragment_two(); transaction.add(R.id.fragme_layout , fragment_two); }else{ transaction.show(fragment_two); } break; case R.id.button_03: if (fragment_my == null){ fragment_my = new Fragment_my(); transaction.add(R.id.fragme_layout , fragment_my); }else{ transaction.show(fragment_my); } break; default: break; } transaction.commit(); } }); } }
这是该fragment的布局,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:background="#D43D3D" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="今日头条" android:textStyle="bold" android:textSize="25dp" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" android:textColor="#ffffff"/> <ImageView android:onClick="sousuo" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@mipmap/sousuokuang" android:layout_marginLeft="10dp" /> LinearLayout> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="50dp" app:tabMode="scrollable" app:tabGravity="center" app:tabIndicatorColor="#E46262" app:tabTextColor="#000000" app:tabSelectedTextColor="#E46262"> android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/view_pager_shou" android:layout_width="match_parent" android:layout_height="match_parent"> android.support.v4.view.ViewPager> LinearLayout>
public class Fragment_shou extends Fragment { private TabLayout tabLayout; private Listlist = new ArrayList<>(); private ViewPager pager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_shou , container , false); tabLayout = (TabLayout) view.findViewById(R.id.tab_layout); pager = (ViewPager) view.findViewById(R.id.view_pager_shou); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); list.add("头条"); list.add("社会"); list.add("国内"); list.add("国际"); list.add("娱乐"); list.add("体育"); list.add("军事"); list.add("科技"); list.add("财经"); list.add("时尚"); //解决tablayout的空数据问题 pager.setOffscreenPageLimit(list.size());
pager.setAdapter(new FragmentPagerAdapter(getFragmentManager()) { @Override public CharSequence getPageTitle(int position) { return list.get(position); } @Override public Fragment getItem(int position) { NewsFragment newsFragment = new NewsFragment(); Bundle bundle = new Bundle(); if (list.get(position).equals("头条")){
-=-=-不行的话就用这行转码,再传过去就能使用了
String s = URLEncoder.encode("福利");bundle.putString("name" , "top");
}else if (list.get(position).equals("社会")){
bundle.putString("name" , "shehui");
}else if (list.get(position).equals("国内")){
bundle.putString("name" , "guonei");
}else if (list.get(position).equals("国际")){
bundle.putString("name" , "guoji");
}else if (list.get(position).equals("娱乐")){
bundle.putString("name" , "yule");
}else if (list.get(position).equals("体育")){
bundle.putString("name" , "tiyu");
}else if (list.get(position).equals("军事")){
bundle.putString("name" , "junshi");
}else if (list.get(position).equals("科技")){
bundle.putString("name" , "keji");
}else if (list.get(position).equals("财经")){
bundle.putString("name" , "caijing");
}else if (list.get(position).equals("时尚")){
bundle.putString("name" , "shishang");
}
newsFragment.setArguments(bundle);
return newsFragment;
}
@Override
public int getCount() {
return list.size();
}
});
//tablayout要与viewpager关联
tabLayout.setupWithViewPager(pager);
}
//搜索的点击事件
public void sousuo(View view){
}
}--------------------------------------tablayout所用到的NewsFragment Xlistview上拉,下拉
布局以下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment.bwie.com.newstopandnewswy.view.XListView android:id="@+id/xlist_view" android:layout_width="match_parent" android:layout_height="match_parent"> fragment.bwie.com.newstopandnewswy.view.XListView> LinearLayout>
public class NewsFragment extends Fragment implements XListView.IXListViewListener { private XListView xListView; private Listlist = new ArrayList<>(); private MyAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.news_fragment , container , false); xListView = (XListView) view.findViewById(R.id.xlist_view); //点击事件 xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> adapterView, View view, int i, long l) { Intent intent = new Intent(getActivity() , WebActivity.class); intent.putExtra("url" , list.get(i).getUrl()); getActivity().startActivity(intent); } }); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //获取,传来的值 Bundle bundle = getArguments(); String string = bundle.getString("name" , "top"); getazong(string); //上拉 xListView.setPullLoadEnable(true); //下拉 xListView.setPullRefreshEnable(true); xListView.setXListViewListener(this); getLoadEnable(); } //获取总的数据 public void getazong(final String string) { AsyncTask asyncTask = new AsyncTask () { @Override protected String doInBackground(Void... voids) { String paht = "http://v.juhe.cn/toutiao/index?type="+string+"&key=c4479ad58f41e7f78a8fa073d0b1f1b5"; try { URL url = new URL(paht); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = StreamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); UserBean userBean = gson.fromJson(s, UserBean.class); //list = null; Log.i("-------" , "list" + list); list.addAll(userBean.getResult().getData()); //设置适配器 getadapter(); } }; asyncTask.execute(); } //上拉 public void getLoadEnable() { } //下拉 public void getRefreshEnable() { } //设置适配器 private void getadapter() { if (adapter == null){ adapter = new MyAdapter(getActivity(), list); xListView.setAdapter(adapter); }else{ adapter.notifyDataSetChanged();; } } //解析 private String StreamToString(InputStream inputStream, String s) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); String string = ""; while ((string = bufferedReader.readLine()) != null){ builder.append(string); } bufferedReader.close(); Log.i("builder" , "builder---->" + builder.toString()); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } @Override public void onRefresh() { getRefreshEnable(); } @Override public void onLoadMore() { getLoadEnable(); } }
-------------------------------------pulltorefreshlistview 上拉,下拉
布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.handmark.pulltorefresh.library.PullToRefreshListView xmlns:ptr="http://schemas.android.com/apk/res-auto" android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/refresh_list_view" ptr:ptrDrawable="@drawable/default_ptr_flip" ptr:ptrAnimationStyle="flip" ptr:ptrHeaderBackground="#383838" ptr:ptrHeaderTextColor="#FFFFFF" > com.handmark.pulltorefresh.library.PullToRefreshListView> LinearLayout>
public class NewsFragment extends Fragment { private PullToRefreshListView pullToRefreshListView; private ILoadingLayout startLabels; private ILoadingLayout endLabels; int num = 1; Listlist = new ArrayList<>(); private MyAdapter myAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.news_fragment, container, false); pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.refresh_list_view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle bundle = getArguments(); final String string = bundle.getString("name","fuli"); getDataFromNet(string); pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); startLabels = pullToRefreshListView.getLoadingLayoutProxy(true, false); startLabels.setPullLabel("上拉刷新"); startLabels.setRefreshingLabel("正在载入..."); startLabels.setReleaseLabel("放开刷新"); endLabels = pullToRefreshListView.getLoadingLayoutProxy(false, true); endLabels.setPullLabel("下拉刷新"); endLabels.setRefreshingLabel("正在载入..."); endLabels.setReleaseLabel("放开刷新..."); pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2 () { @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { num ++; getRefreshData(string); } @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { num = 1; getData(string); } }); pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> adapterView, View view, int i, long l) { Intent intent = new Intent(getActivity() , WebActivity.class); intent.putExtra("url" , list.get(i-1).getUrl()); startActivity(intent); } }); } private void getDataFromNet(final String string) { AsyncTask asyncTask = new AsyncTask () { @Override protected String doInBackground(Void... voids) { String path = "http://gank.io/api/data/"+string+"/10/1"; try { URL url = new URL(path); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = urlConnection.getInputStream(); String json = streamTostring(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); Bean bean = gson.fromJson(s, Bean.class); list.addAll(0 , bean.getResults()); myAdapter = new MyAdapter(list, getActivity()); pullToRefreshListView.setAdapter(myAdapter); } }; asyncTask.execute(); } private String streamTostring(InputStream inputStream, String s) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); String string = null; while ((string = bufferedReader.readLine()) != null) { builder.append(string); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } private void getRefreshData(final String string) { //1.创建异步任务的对象..第一个参数url路径Void,第二个参数表示进度Void,第三个参数返回值类型String(可以为空) AsyncTask asyncTask = new AsyncTask () { //执行耗时的网络操作 @Override protected String doInBackground(Void... voids) { String path = "http://gank.io/api/data/"+string+"/10/" + num; //1.url try { URL url = new URL(path); //2.打开 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置 connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); //获取 int responseCode = connection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = connection.getInputStream(); //字节流转为字符串 String json = streamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } //主线程,,,解析返回的数据 @Override protected void onPostExecute(String json) { //解析 Gson gson = new Gson(); Bean bean = gson.fromJson(json, Bean.class); //dataDataBean.getNewslist(); //把解析的数据添加到集合中 list.addAll(0, bean.getResults()); setAdapter(); //刷新停止 pullToRefreshListView.onRefreshComplete(); //设置本次刷新的时间 Date date = new Date(System.currentTimeMillis()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm"); startLabels.setLastUpdatedLabel("上次刷新时间:" + simpleDateFormat.format(date)); } }; //2.执行任务 asyncTask.execute(); } public void getData(final String string) { //1.创建异步任务的对象..第一个参数url路径Void,第二个参数表示进度Void,第三个参数返回值类型String(可以为空) AsyncTask asyncTask = new AsyncTask () { //执行耗时的网络操作 @Override protected String doInBackground(Void... voids) { String path = "http://gank.io/api/data/"+string+"/10/" + num; //1.url try { URL url = new URL(path); //2.打开 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置 connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); //获取 int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); //字节流转为字符串 String json = streamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } //主线程,,,解析返回的数据 @Override protected void onPostExecute(String json) { //解析 Gson gson = new Gson(); Bean dataDataBean = gson.fromJson(json, Bean.class); //dataDataBean.getNewslist(); //把解析的数据添加到集合中 list.addAll(dataDataBean.getResults()); setAdapter(); //刷新停止 pullToRefreshListView.onRefreshComplete(); } }; //2.执行任务 asyncTask.execute(); } private String streamToString(InputStream inputStream,String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null){ builder.append(s); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } private void setAdapter() { if (myAdapter == null){ myAdapter = new MyAdapter(list, getActivity()); pullToRefreshListView.setAdapter(myAdapter); }else { myAdapter.notifyDataSetChanged(); } } }
--------------------------跳转到的WebAtivity
布局
xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent">WebView> LinearLayout>
public class WebActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.web_activity); webView = (WebView) findViewById(R.id.web_view); Intent intent = getIntent(); String url = intent.getStringExtra("url"); //加载 webView.loadUrl(url); //设置 webView.setWebViewClient(new WebViewClient()); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); } }
---------------------------------------第二个fragment
布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#EB413D"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="今日要闻" android:textSize="20dp" android:padding="10dp" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" android:textColor="#ffffff"/> LinearLayout> <android.support.v4.view.ViewPager android:layout_below="@id/layout" android:id="@+id/view_pager_two" android:layout_width="match_parent" android:layout_height="200dp"> android.support.v4.view.ViewPager> <TextView android:id="@+id/text_view" android:layout_alignBottom="@id/view_pager_two" android:layout_width="wrap_content" android:text="sdasda" android:textSize="20sp" android:padding="10dp" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/linear_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/view_pager_two" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" android:orientation="horizontal" android:layout_alignParentRight="true"> LinearLayout> <fragment.bwie.com.newstopandnewswy.view.XListView android:layout_below="@id/text_view" android:id="@+id/xlist_view_two" android:layout_width="match_parent" android:layout_height="match_parent"> fragment.bwie.com.newstopandnewswy.view.XListView> RelativeLayout>
==============================================小圆点的布局选中和未选中的布局
---------------------doc_select
xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#ff0000"/> <corners android:radius="5dp"/> <size android:height="10dp" android:width="10dp"/> shape>-----------------------doc_select_no
xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#00ff00"/> <corners android:radius="5dp"/> <size android:height="10dp" android:width="10dp"/> shape>
public class Fragment_two extends Fragment implements XListView.IXListViewListener { private ViewPager pager; private XListView xListView; private TextView textView; private LinearLayout linearLayout; private Listimages; private List lists = new ArrayList<>(); private List list; private int page = 1; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0){ int currentItem = pager.getCurrentItem(); pager.setCurrentItem(currentItem+1); handler.sendEmptyMessageDelayed(0 , 2000); } } }; private MyAdapter_Two adapter_two; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_two , container , false); pager = (ViewPager) view.findViewById(R.id.view_pager_two); xListView = (XListView) view.findViewById(R.id.xlist_view_two); textView = (TextView) view.findViewById(R.id.text_view); linearLayout = (LinearLayout) view.findViewById(R.id.linear_layout); //点击事件 xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> adapterView, View view, int i, long l) { Intent intent = new Intent(getActivity() , WebActivity.class); intent.putExtra("url" , list.get(i).getUrl()); getActivity().startActivity(intent); } }); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //无限轮播 wuxianviewpager(); //上拉 xListView.setPullLoadEnable(true); //下拉 xListView.setPullRefreshEnable(true); xListView.setXListViewListener(this); getRefreshEnable(); } private void wuxianviewpager() { AsyncTask asyncTask = new AsyncTask () { @Override protected String doInBackground(Void... voids) { String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=6&page=1"; try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = StreamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); UserBean02 userBean02 = gson.fromJson(s, UserBean02.class); list = userBean02.getNewslist(); for (int i = 0; i < list.size() ; i ++){ lists.add(list.get(i).getPicUrl()); } //初始化小圆点 MyPagerAdapter adapter = new MyPagerAdapter(getActivity(), list, handler); pager.setAdapter(adapter); //初始化小圆点 initDoc(); //设置ViewPager初始展示的位置 pager.setCurrentItem(lists.size()*10000); //发送延时消息 handler.sendEmptyMessageDelayed(0 , 2000); //viewPager页面改变的监听事件 pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { textView.setText(list.get(position% list.size()).getTitle()); //如果选中了这一页,,,当前小圆点红色,,,否则绿色 for (int i = 0;i<images.size();i++){ if (i== position%images.size()){ images.get(i).setImageResource(R.drawable.doc_select); }else { images.get(i).setImageResource(R.drawable.doc_select_no); } } } @Override public void onPageScrollStateChanged(int state) {
} }); } }; asyncTask.execute(); } private String StreamToString(InputStream inputStream, String s) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); String string = ""; while ((string=bufferedReader.readLine()) != null){ builder.append(string); } bufferedReader.close(); Log.i("builder" , "builder---->" + builder.toString()); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } //初始化小圆点 private void initDoc() { //首先需要一个集合记录这些小圆点的图片,,,,当页面切换的时候,可以从集合中取出imageView进行显示图片的设置 images = new ArrayList<>(); linearLayout.removeAllViews();//清空/移除所有的view for (int i = 0;i<lists.size();i++){ ImageView imageView = new ImageView(getActivity()); if (i==0){//显示第一页,,,红的 imageView.setImageResource(R.drawable.doc_select); }else {//绿的 imageView.setImageResource(R.drawable.doc_select_no); } //添加到集合 images.add(imageView); //加入到线性布局中显示 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(5,0,5,0); linearLayout.addView(imageView,params); } } //设置适配器 private void getadapter() { if (adapter_two == null){ adapter_two = new MyAdapter_Two(getActivity(), list); xListView.setAdapter(adapter_two); }else{ adapter_two.notifyDataSetChanged();; } } //下拉 public void getRefreshEnable() { AsyncTaskasyncTask = new AsyncTask () { @Override protected String doInBackground(Void... voids) { String paht = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=6&page=" + page; try { URL url = new URL(paht); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = StreamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); UserBean02 userBean02 = gson.fromJson(s, UserBean02.class); list.addAll(0 , userBean02.getNewslist()); //设置适配器 getadapter(); //停止 xListView.stopRefresh(); Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); //设置时间 xListView.setRefreshTime(dateFormat.format(date)); } }; asyncTask.execute(); } //上拉 public void getLoadEnable() { AsyncTask asyncTask = new AsyncTask () { @Override protected String doInBackground(Void... voids) { String paht = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=6&page=" + page; try { URL url = new URL(paht); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = StreamToString(inputStream, "utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); UserBean02 userBean02 = gson.fromJson(s, UserBean02.class); list.addAll(userBean02.getNewslist()); //设置适配器 getadapter(); //停止刷新 xListView.stopLoadMore(); } }; asyncTask.execute(); } //下拉 @Override public void onRefresh() { page ++; Log.i("num" , "下拉num---->" + page); getRefreshEnable(); } //上拉 @Override public void onLoadMore() { page = 1; Log.i("num" , "上拉num---->" + page); getLoadEnable(); } }
---------------------------第三个Fragment
布局
public class Fragment_my extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my , container , false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }--------------------------所有用到的adapter----------------------------xlistview所需的string.xml里的东西****FragmentViewPagerAdapter fragment的适配器
public class FragmentViewPagerAdapter extends FragmentPagerAdapter { Context context; Listlist; public FragmentViewPagerAdapter(FragmentManager context, List list) { super(context); this.list = list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } } ****MyAdapter 多条目加载的适配器
public class MyAdapter extends BaseAdapter { Context context; List****MyPagerAdapter 无线轮播的适配器list; private static final int IMAGE_ITEM_LEFT = 0; private static final int IMAGE_ITEM_RIGHT = 1; public MyAdapter(Context context, List list) { this.context = context; this.list = list; ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context)); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { if ((position%2) == 0){ return IMAGE_ITEM_LEFT; } return IMAGE_ITEM_RIGHT; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if (getItemViewType(i) == IMAGE_ITEM_LEFT){ ViewHolderLeft holderLeft; if (view == null){ holderLeft = new ViewHolderLeft(); view = View.inflate(context , R.layout.image_left , null); holderLeft.textView = (TextView) view.findViewById(R.id.text_title); holderLeft.imageView = (ImageView) view.findViewById(R.id.iamge_01); view.setTag(holderLeft); }else{ holderLeft = (ViewHolderLeft) view.getTag(); } holderLeft.textView.setText(list.get(i).getTitle()); ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s() , holderLeft.imageView); }else{ ViewHolderRight holderRight; if (view == null){ holderRight = new ViewHolderRight(); view = View.inflate(context , R.layout.image_right , null); holderRight.textView = (TextView) view.findViewById(R.id.text_title); holderRight.imageView = (ImageView) view.findViewById(R.id.iamge_02); view.setTag(holderRight); }else{ holderRight = (ViewHolderRight) view.getTag(); } holderRight.textView.setText(list.get(i).getTitle()); ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s() , holderRight.imageView); } return view; } class ViewHolderLeft{ ImageView imageView; TextView textView; } class ViewHolderRight{ TextView textView; ImageView imageView; } } public class MyPagerAdapter extends PagerAdapter { Context context; Listlist; Handler handler; public MyPagerAdapter(Context context, List list, Handler handler) { this.context = context; this.list = list; this.handler = handler; ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context)); } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, final int position) { ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.FIT_XY); ImageLoader.getInstance().displayImage(list.get(position%list.size()).getPicUrl() , imageView); //imageView触摸的监听事件 imageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { boolean isTiaozhuan = true; switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN://按下 Log.i("-----" , "ACTION_DOWN"); handler.removeCallbacksAndMessages(null); break; case MotionEvent.ACTION_MOVE://移动 Log.i("-----" , "ACTION_MOVE"); isTiaozhuan = false; handler.removeCallbacksAndMessages(null); break; case MotionEvent.ACTION_CANCEL://取消 Log.i("-----" , "ACTION_CANCEL"); isTiaozhuan = false; handler.sendEmptyMessageDelayed(0 , 2000); break; case MotionEvent.ACTION_UP://抬起 Log.i("-----" , "ACTION_UP"); if (isTiaozhuan){ Toast.makeText(context , "跳转页面" , Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context , WebActivity.class); intent.putExtra("url" , list.get(position%list.size()).getUrl()); context.startActivity(intent); } handler.sendEmptyMessageDelayed(1 , 2000); break; default: break; } //自己处理触摸事件....如果当前位置返回了true,,,点击事件将不会执行,,,表示动作自己处理,不会传递 return true; } }); //添加到容器 container.addView(imageView); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } ----------------------------------imageloader自定义的分类 在清单文件要添加name=".BaseApplicent"
**----BaseApplicent
public class BaseApplicent extends Application { @Override public void onCreate() { super.onCreate(); ImafeLoaderUtil.initConfig(this); } }**----ImafeLoaderUtil
public class ImafeLoaderUtil { public static void initConfig(Context context) { File cacheDir = StorageUtils.getCacheDirectory(context); //缓存文件夹路径 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .threadPoolSize(3) // default 线程池内加载的数量 .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级 .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现 .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值 .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径 .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 .diskCacheFileCount(100) // 可以缓存的文件数量 // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密 .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .imageDownloader(new BaseImageDownloader(context)) // default .imageDecoder(new BaseImageDecoder(true)) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() // 打印debug log .build(); //开始构建 ImageLoader.getInstance().init(config); } }
<string name="xlistview_header_hint_normal">下拉刷新string> <string name="xlistview_header_hint_ready">松开刷新数据string> <string name="xlistview_header_hint_loading">正在加载...string> <string name="xlistview_header_last_time">上次更新时间:string> <string name="xlistview_footer_hint_normal">查看更多string> <string name="xlistview_footer_hint_ready">松开载入更多string>************build.gradle的一部分 只供参考 注意要把26改为25
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:25.+' compile 'com.android.support:design:25.3.1' <--!tablayout--> compile 'com.google.code.gson:gson:2.8.1' <--!gson--> compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' <--!imageload--> }
*1.去标题 在style里面建一个
<style name="NoTitleTheme" parent="Theme.AppCompat.Light.NoActionBar"> style>*2.然后在清单里调用,这样是全部都去标题,可以谁去谁调用他android:theme="@style/NoTitleTheme"