AndroidStudio——今日头条(可以实时获取数据的app)
今日头条包含以下模块:
首页 视频 天气 和 我的
其中 首页用于加载实时的新闻频道及内容,可以实现点击图片查看图片详情,并且可以实现内容的收藏与取消收藏
视频模块暂时未加入任何内容
天气模块可以实现天气的实时更新,最多可以显示最近三天的天气情况
我的 模块中 点击收藏,可以查看收藏的新闻内容
**Activity代码:**
MainActivity
public class MainActivity extends AppCompatActivity {private FragmentTabHost ft;private String[] str = {"首页", "视频", "天气", "我的"};private int[] imgRes = {R.drawable.home, R.drawable.video, R.drawable.topic,R.drawable.my};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ft = (FragmentTabHost) findViewById(R.id.ft);getSupportActionBar().hide();init();}public void init() {//装配ft.setup(this, getSupportFragmentManager(), R.id.fl);Fragment home = new HomeFragment();//TabSpec标签说明TabHost.TabSpec tabSpec0 =ft.newTabSpec(str[0]).setIndicator(getView(0));ft.addTab(tabSpec0, home.getClass(), null);Fragment video = new VideoFragment();TabHost.TabSpec tabSpec1 =ft.newTabSpec(str[1]).setIndicator(getView(1));ft.addTab(tabSpec1, video.getClass(), null);Fragment topic = new TopicFragment();TabHost.TabSpec tabSpec2 =ft.newTabSpec(str[2]).setIndicator(getView(2));ft.addTab(tabSpec2, topic.getClass(), null);Fragment my = new MyFragment();TabHost.TabSpec tabSpec3 =ft.newTabSpec(str[3]).setIndicator(getView(3));ft.addTab(tabSpec3, my.getClass(), null);}public View getView(int i) {View v = getLayoutInflater().inflate(R.layout.tab_layout, null);ImageView iv = (ImageView) v.findViewById(R.id.iv);TextView tv = (TextView) v.findViewById(R.id.tv);iv.setImageResource(imgRes[i]);tv.setText(str[i]);return v;}
}
ContentActivity
public class ContentActivity extends AppCompatActivity {
private WebView wv;
private ImageView back;
private TextView title, collection;
private boolean isExisits;
private NewsDao newsDao;
private String titles;
//全局变量自动赋值 局部变量不可以
private MyNews news;
@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_content);getSupportActionBar().hide();wv = (WebView) findViewById(R.id.wv);back = (ImageView) findViewById(R.id.back);title = (TextView) findViewById(R.id.title);collection = (TextView) findViewById(R.id.collection);//getIntent()是将该项目中包含的原始intent检索出来//将检索出来的intent赋值给一个Intent类型的变量intentIntent intent = getIntent();String html = "";titles = "";if (intent != null) {news = intent.getParcelableExtra("news");html = news.getHtml();titles = news.getTitle();}title.setText(titles);WebSettings ws = wv.getSettings();//支持放大ws.setSupportZoom(true);//显示放大缩小的控件 一个加号一个减号ws.setDisplayZoomControls(true);ws.setJavaScriptEnabled(true);ws.setDefaultTextEncodingName("utf-8");//放大多少倍//ws.setTextZoom(20);wv.loadDataWithBaseURL("", html, "text/html", "utf-8", "");//设置内容的背景颜色wv.setBackgroundColor(getResources().getColor(R.color.background));newsDao = new NewsDao(this);//判断新闻是否收藏过checkNews(titles);back.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {finish();}});collection.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if(isExisits){newsDao.deleteNews(news.getTitle());collection.setText("取消收藏");}else {newsDao.addNews(news);collection.setText("收藏");}checkNews(news.getTitle());}});
}public void checkNews(String title) {MyNews myNews = newsDao.searchNews(title);// MyNews myNews = new MyNews();if (myNews == null) {collection.setText("收藏");isExisits = false;} else {collection.setText("取消收藏");isExisits = true;}
}
}
ImgActivity
public class ImgActivity extends AppCompatActivity {private PhotoViewPager pvp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_img);getSupportActionBar().hide();pvp = (PhotoViewPager) findViewById(R.id.pvp);Intent intent = getIntent();String imgUrls = intent.getStringExtra("img");List<PhotoView> pvList = new ArrayList<>();List imgList = paserImageList(imgUrls);for (int i = 0; i < imgList.size(); i++) {PhotoView pv = new PhotoView(this);pv.setScaleType(ImageView.ScaleType.CENTER_CROP);Glide.with(this).load(imgList.get(i)).into(pv);pvList.add(pv);}pvp.setAdapter(new MyViewPagerAdapter(pvList));}public List paserImageList(String imgList) {List img = new ArrayList();try {JSONArray ja = new JSONArray(imgList);for (int i = 0; i < ja.length(); i++) {JSONObject obj = (JSONObject) ja.get(i);if (obj.has("url")) {img.add(obj.getString("url"));}}} catch (JSONException e) {e.printStackTrace();}return img;}public class MyViewPagerAdapter extends PagerAdapter {private List<PhotoView> myData;public MyViewPagerAdapter(List<PhotoView> myData) {this.myData = myData;}@Overridepublic int getCount() {return myData.size();}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}//自己写的@Overridepublic Object instantiateItem(ViewGroup container, int position) {container.addView(myData.get(position));return myData.get(position);}//自己写的@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {container.removeView(myData.get(position));}}
}
CollectionActivity
public class CollectionActivity extends AppCompatActivity {private ListView lv;private List<MyNews> list;private NewsDao newsDao;private NewsBaseAdapter na;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_collection);lv = (ListView) findViewById(R.id.lv);list = new ArrayList<>();na = new NewsBaseAdapter(list, this);lv.setAdapter(na);newsDao = new NewsDao(this);getList();}public void getList() {//先清空 避免叠加list.clear();//list=List不可用 由于不能触发na.notifyDataSetChanged();所以导致布局加载不出数据来list.addAll(newsDao.searchNews());na.notifyDataSetChanged();}@Overrideprotected void onStart() {super.onStart();getList();}
}
**adapter 代码**
MyTabHostAdapter
public class MyTabHostAdapter extends FragmentPagerAdapter {private List<Fragment> list;public MyTabHostAdapter(FragmentManager fm, List<Fragment> list) {super(fm);this.list = list;}@Overridepublic Fragment getItem(int position) {return list.get(position);}@Overridepublic int getCount() {return list.size();}
}
NewsBaseAdapter
public class NewsBaseAdapter extends BaseAdapter {private List<MyNews> myNews;private Context context;//常量必须从0开始 并且不能跳着来不能0,2,4...private final int TYPE0 = 0;private final int TYPE1 = 1;private final int TYPE2 = 2;private final int TYPE3 = 3;public NewsBaseAdapter(List<MyNews> myNews, Context context) {this.myNews = myNews;this.context = context;}@Overridepublic int getCount() {return myNews.size();}@Overridepublic Object getItem(int position) {return myNews.get(position);}@Overridepublic long getItemId(int position) {return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {final ViewHolder vh;int type = getItemViewType(position);if (convertView == null) {vh = new ViewHolder();if (type == 3) {convertView = LayoutInflater.from(context).inflate(R.layout.my_news_layout3, null);vh.title = (TextView) convertView.findViewById(R.id.title);vh.pubDate = (TextView) convertView.findViewById(R.id.pubDate);vh.source = (TextView) convertView.findViewById(R.id.source);vh.img = (ImageView) convertView.findViewById(R.id.img);vh.img2 = (ImageView) convertView.findViewById(R.id.img2);vh.img3 = (ImageView) convertView.findViewById(R.id.img3);vh.img.setOnClickListener(new ClickLisner(position));vh.img2.setOnClickListener(new ClickLisner(position));vh.img3.setOnClickListener(new ClickLisner(position));convertView.setTag(vh);} else if (type == 2) {convertView = LayoutInflater.from(context).inflate(R.layout.my_news_layout2, null);vh.title = (TextView) convertView.findViewById(R.id.title);vh.pubDate = (TextView) convertView.findViewById(R.id.pubDate);vh.source = (TextView) convertView.findViewById(R.id.source);vh.img = (ImageView) convertView.findViewById(R.id.img);vh.img2 = (ImageView) convertView.findViewById(R.id.img2);vh.img.setOnClickListener(new ClickLisner(position));vh.img2.setOnClickListener(new ClickLisner(position));convertView.setTag(vh);} else if (type == 1) {convertView = LayoutInflater.from(context).inflate(R.layout.my_news_layout1, null);vh.title = (TextView) convertView.findViewById(R.id.title);vh.pubDate = (TextView) convertView.findViewById(R.id.pubDate);vh.source = (TextView) convertView.findViewById(R.id.source);vh.img = (ImageView) convertView.findViewById(R.id.img);vh.img.setOnClickListener(new ClickLisner(position));convertView.setTag(vh);} else {convertView = LayoutInflater.from(context).inflate(R.layout.my_news_layout, null);vh.title = (TextView) convertView.findViewById(R.id.title);vh.pubDate = (TextView) convertView.findViewById(R.id.pubDate);vh.source = (TextView) convertView.findViewById(R.id.source);convertView.setTag(vh);}} else {vh = (ViewHolder) convertView.getTag();}//通过这一句知道要加载哪个频道的newsMyNews news = myNews.get(position);if (type == 3) {vh.title.setText(news.getTitle());vh.source.setText(news.getSource());vh.pubDate.setText(news.getPubDate());List list = paserImageList(news.getImageurls());if (list.size() == 3) {Glide.with(context).load(list.get(0)).into(vh.img);Glide.with(context).load(list.get(1)).into(vh.img2);Glide.with(context).load(list.get(2)).into(vh.img3);}} else if (type == 2) {vh.title.setText(news.getTitle());vh.source.setText(news.getSource());vh.pubDate.setText(news.getPubDate());List list = paserImageList(news.getImageurls());if (list.size() == 2) {Glide.with(context).load(list.get(0)).into(vh.img);Glide.with(context).load(list.get(1)).into(vh.img2);}} else if (type == 1) {vh.title.setText(news.getTitle());vh.source.setText(news.getSource());vh.pubDate.setText(news.getPubDate());List list = paserImageList(news.getImageurls());if (list.size() == 1) {Glide.with(context).load(list.get(0)).into(vh.img);}} else {vh.title.setText(news.getTitle());vh.source.setText(news.getSource());vh.pubDate.setText(news.getPubDate());}convertView.setOnClickListener(new ClickLisner(position));return convertView;}public class ClickLisner implements View.OnClickListener {private int position;//在类里生成构造 把position传进来public ClickLisner(int position) {this.position = position;}@Overridepublic void onClick(View v) {int id=v.getId();if(id==R.id.img||id==R.id.img2||id==R.id.img3){Intent intent=new Intent(context, ImgActivity.class);intent.putExtra("img",myNews.get(position).getImageurls());context.startActivity(intent);}else{MyNews news = myNews.get(position);// Log.d("======", news.getHtml());Intent intent = new Intent(context, ContentActivity.class);//MyNews要实现序列化intent.putExtra("news", news);context.startActivity(intent);}}}public class ViewHolder {TextView pubDate;TextView title;ImageView img;TextView source;ImageView img2;ImageView img3;}@Overridepublic int getItemViewType(int position) {List list = paserImageList(myNews.get(position).getImageurls());if (list.size() == 3) {return TYPE3;} else if (list.size() == 1) {return TYPE1;} else if (list.size() == 2) {return TYPE2;} else {return TYPE0;}}@Overridepublic int getViewTypeCount() {return 4;}public List paserImageList(String imgList) {List img = new ArrayList();try {JSONArray ja = new JSONArray(imgList);for (int i = 0; i < imgList.length(); i++) {JSONObject obj = (JSONObject) ja.get(i);if (obj.has("url")) {img.add(obj.getString("url"));}}} catch (JSONException e) {e.printStackTrace();}return img;}}
NewsFragmentAdapter
public class NewsFragmentAdapter extends FragmentPagerAdapter {private List<Fragment> fragmentList;private List<String> titles;public NewsFragmentAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titles) {//public NewsFragmentAdapter(List<News> fm,FragmentActivity fragmentList) {super(fm);this.fragmentList = fragmentList;this.titles = titles;}@Overridepublic Fragment getItem(int position) {return fragmentList.get(position);}@Overridepublic int getCount() {return fragmentList.size();}@Overridepublic CharSequence getPageTitle(int position) {return titles.get(position);}
}
**dao文件**
NewsDao
public class NewsDao {private MyDbHelper myDbHelper;public NewsDao(Context context) {myDbHelper = new MyDbHelper(context);}//收藏新闻public void addNews(MyNews myNews) {SQLiteDatabase db = myDbHelper.getWritableDatabase();ContentValues cv = new ContentValues();cv.put("title", myNews.getTitle());cv.put("pubDate", myNews.getPubDate());cv.put("source", myNews.getSource());cv.put("html", myNews.getHtml());cv.put("imageurls", myNews.getImageurls());db.insert("news", null, cv);db.close();}//查询所有收藏public List searchNews() {SQLiteDatabase db = myDbHelper.getReadableDatabase();Cursor cs = db.query("news", null, null, null, null, null, null);MyNews myNews = null;List<MyNews> list = new ArrayList<>();while (cs.moveToNext()) {myNews = new MyNews();// cs.getColumnIndex("_id") id 这一列结果中的下标myNews.setTitle(cs.getString(cs.getColumnIndex("title")));myNews.setSource(cs.getString(cs.getColumnIndex("source")));myNews.setPubDate(cs.getString(cs.getColumnIndex("pubDate")));myNews.setHtml(cs.getString(cs.getColumnIndex("html")));myNews.setImageurls(cs.getString(cs.getColumnIndex("imageurls")));list.add(myNews);}cs.close();db.close();return list;}//查询一条收藏public MyNews searchNews(String title) {SQLiteDatabase db = myDbHelper.getWritableDatabase();Cursor cs = db.query("news", null, "title = ? ", new String[]{title}, null, null, null);MyNews myNews = null;if (cs.moveToNext()) {myNews = new MyNews();// cs.getColumnIndex("_id") id 这一列结果中的下标myNews.setTitle(cs.getString(cs.getColumnIndex("title")));myNews.setSource(cs.getString(cs.getColumnIndex("source")));myNews.setPubDate(cs.getString(cs.getColumnIndex("pubDate")));myNews.setHtml(cs.getString(cs.getColumnIndex("html")));myNews.setImageurls(cs.getString(cs.getColumnIndex("imageurls")));}cs.close();db.close();return myNews;}// 取消收藏public void deleteNews(String title) {SQLiteDatabase db = myDbHelper.getWritableDatabase();db.delete("news", "title= ? ", new String[]{title});db.close();}}
NewsCacheDao
public class NewsCacheDao {private Context context;private Dao<MyNews, Integer> newsDao;private DatabaseHelper helper;public NewsCacheDao(Context context) {this.context = context;helper = (DatabaseHelper) DatabaseHelper.getHelper(context);try {newsDao = helper.getDao(MyNews.class);} catch (SQLException e) {e.printStackTrace();}}public void addNews(MyNews news) {try {//根据主键来判断是更新还是修改 因此一定要有主键newsDao.createOrUpdate(news);} catch (SQLException e) {e.printStackTrace();}}//根据id查找新闻public ArrayList<MyNews> searchNews(String chId) {try {return (ArrayList<MyNews>) newsDao.queryBuilder().where().eq("channelId", chId).query();} catch (SQLException e) {e.printStackTrace();}return null;}
}
WeatherCacheDao
public class WeatherCacheDao {private Context context;private Dao<Weather, Integer> weatherDao;private DatabaseHelper helper;public WeatherCacheDao(Context context) {this.context = context;helper = (DatabaseHelper) DatabaseHelper.getHelper(context);try {weatherDao = helper.getDao(Weather.class);} catch (SQLException e) {e.printStackTrace();}}public void addWeather(Weather weather) {try {//根据主键来判断是更新还是修改 因此一定要有主键weatherDao.createOrUpdate(weather);} catch (SQLException e) {e.printStackTrace();}}//查询所有public List<Weather> searchWeather() {try {return weatherDao.queryForAll();} catch (SQLException e) {e.printStackTrace();}return null;}public void deleteAll(){try {weatherDao.deleteBuilder().delete();} catch (SQLException e) {e.printStackTrace();}}
}
**dataBaseHelper文件**
DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {private static final String TABLE_NAME = "ormtest.db";private Map<String, Dao> daos = new HashMap<String, Dao>();private static DatabaseHelper instance;private DatabaseHelper(Context context) {super(context, TABLE_NAME, null, 2);}@Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {try {TableUtils.createTable(connectionSource, MyNews.class);TableUtils.createTable(connectionSource, Weather.class);} catch (SQLException e) {e.printStackTrace(); } }@Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {try {//匹配User.class类TableUtils.dropTable(connectionSource, MyNews.class, true);TableUtils.dropTable(connectionSource, Weather.class, true);onCreate(database, connectionSource);} catch (SQLException e) {e.printStackTrace(); } }/** * 单例获取该Helper * * @param context * @return */ public static synchronized DatabaseHelper getHelper(Context context) {context = context.getApplicationContext(); if (instance == null) {synchronized (DatabaseHelper.class) {if (instance == null) {instance = new DatabaseHelper(context);}} }return instance; }public synchronized Dao getDao(Class clazz) throws SQLException {Dao dao = null;String className = clazz.getSimpleName();if (daos.containsKey(className)) {dao = daos.get(className); } if (dao == null) {dao = super.getDao(clazz); daos.put(className, dao); } return dao; }/** * 释放资源 */ @Override public void close() {super.close();for (String key : daos.keySet()) {Dao dao = daos.get(key);dao = null; } }
}
MyDbHelper
public class MyDbHelper extends SQLiteOpenHelper {private final String DBNAME = "MyNews.db";private final String TABLE_NAME = "news";//在SQLite里用作特殊标识的要加下划线(主键)private final String INFO_COLUM_ID = "nid";private final String INFO_COLUM_TITLE = "title";private final String INFO_COLUM_HTML = "html";private final String INFO_COLUM_PUBDATE = "pubDate";private final String INFO_COLUM_SOURCE = "source";private final String INFO_COLUM_IMG = "imageurls";public MyDbHelper(Context context) {//版本号不能为0super(context, "MyNews.db", null, 1);}public MyDbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);}@Overridepublic void onCreate(SQLiteDatabase db) {//如果没有数据库及数据表 就会在OnCreate里自动创建StringBuilder sql = new StringBuilder();sql.append("Create table if not exists ");sql.append(TABLE_NAME + " ( ");// autoincrement 这一行自动增长//sql.append(INFO_COLUM_ID + " varchar(50) primary key ,");sql.append(INFO_COLUM_TITLE + " varchar(100) primary key ,");sql.append(INFO_COLUM_HTML + " varchar(5000),");sql.append(INFO_COLUM_PUBDATE + " varchar(20),");sql.append(INFO_COLUM_SOURCE + " varchar(20),");sql.append(INFO_COLUM_IMG + " varchar(500)");sql.append(" ) ");//执行SQLdb.execSQL(sql.toString());}//数据库更新升级// 通过版本号Version 删除以前的表 然后重新调用OnCreate@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//删除表(delete是删除表里的数据)String sql = " drop table if exists " + TABLE_NAME;db.execSQL(sql);onCreate(db);}
}
**entity文件**
MyNews
@DatabaseTable(tableName = "newsCache")
public class MyNews implements Parcelable{@DatabaseFieldprivate String pubDate;@DatabaseField(id=true)private String title;private String channelName;private String desc;@DatabaseFieldprivate String source;@DatabaseFieldprivate String channelId;private String link;@DatabaseFieldprivate String html;private List<String> allList;@DatabaseFieldprivate String imageurls;private String nid;public MyNews() {}protected MyNews(Parcel in) {pubDate = in.readString();title = in.readString();channelName = in.readString();desc = in.readString();source = in.readString();channelId = in.readString();link = in.readString();html = in.readString();allList = in.createStringArrayList();imageurls = in.readString();nid = in.readString();}public static final Creator<MyNews> CREATOR = new Creator<MyNews>() {@Overridepublic MyNews createFromParcel(Parcel in) {return new MyNews(in);}@Overridepublic MyNews[] newArray(int size) {return new MyNews[size];}};@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeString(pubDate);dest.writeString(title);dest.writeString(channelName);dest.writeString(desc);dest.writeString(source);dest.writeString(channelId);dest.writeString(link);dest.writeString(html);dest.writeStringList(allList);dest.writeString(imageurls);dest.writeString(nid);}public String getPubDate() {return pubDate;}public String getTitle() {return title;}public String getChannelName() {return channelName;}public String getDesc() {return desc;}public String getSource() {return source;}public String getChannelId() {return channelId;}public String getLink() {return link;}public String getHtml() {return html;}public List<String> getAllList() {return allList;}public String getImageurls() {return imageurls;}public String getNid() {return nid;}public static Creator<MyNews> getCREATOR() {return CREATOR;}public void setPubDate(String pubDate) {this.pubDate = pubDate;}public void setTitle(String title) {this.title = title;}public void setChannelName(String channelName) {this.channelName = channelName;}public void setDesc(String desc) {this.desc = desc;}public void setSource(String source) {this.source = source;}public void setChannelId(String channelId) {this.channelId = channelId;}public void setLink(String link) {this.link = link;}public void setHtml(String html) {this.html = html;}public void setAllList(List<String> allList) {this.allList = allList;}public void setImageurls(String imageurls) {this.imageurls = imageurls;}public void setNid(String nid) {this.nid = nid;}
}
Weather
@DatabaseTable
public class Weather implements Parcelable{@DatabaseField(id=true)private String date; //日期@DatabaseFieldprivate String text_day; //白天天气现象文字@DatabaseFieldprivate String code_day; //白天天气现象代码@DatabaseFieldprivate String text_night; //晚间天气现象文字@DatabaseFieldprivate String code_night; //晚间天气现象代码private String high; //当天最高温度private String low; //当天最低温度private String precip; //降水概率,范围0~100,单位百分比private String wind_direction; //风向文字private String wind_direction_degree; //风向角度,范围0~360private String wind_speed; //风速,单位km/h(当unit=c时)、mph(当unit=f时)private String wind_scale; //风力等级public Weather() {}protected Weather(Parcel in) {date = in.readString();text_day = in.readString();code_day = in.readString();text_night = in.readString();code_night = in.readString();high = in.readString();low = in.readString();precip = in.readString();wind_direction = in.readString();wind_direction_degree = in.readString();wind_speed = in.readString();wind_scale = in.readString();}public static final Creator<Weather> CREATOR = new Creator<Weather>() {@Overridepublic Weather createFromParcel(Parcel in) {return new Weather(in);}@Overridepublic Weather[] newArray(int size) {return new Weather[size];}};public String getDate() {return date;}public String getText_day() {return text_day;}public String getCode_day() {return code_day;}public String getText_night() {return text_night;}public String getCode_night() {return code_night;}public String getHigh() {return high;}public String getLow() {return low;}public String getPrecip() {return precip;}public String getWind_direction() {return wind_direction;}public String getWind_direction_degree() {return wind_direction_degree;}public String getWind_speed() {return wind_speed;}public String getWind_scale() {return wind_scale;}public void setDate(String date) {this.date = date;}public void setText_day(String text_day) {this.text_day = text_day;}public void setCode_day(String code_day) {this.code_day = code_day;}public void setText_night(String text_night) {this.text_night = text_night;}public void setCode_night(String code_night) {this.code_night = code_night;}public void setHigh(String high) {this.high = high;}public void setLow(String low) {this.low = low;}public void setPrecip(String precip) {this.precip = precip;}public void setWind_direction(String wind_direction) {this.wind_direction = wind_direction;}public void setWind_direction_degree(String wind_direction_degree) {this.wind_direction_degree = wind_direction_degree;}public void setWind_speed(String wind_speed) {this.wind_speed = wind_speed;}public void setWind_scale(String wind_scale) {this.wind_scale = wind_scale;}@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeString(date);dest.writeString(text_day);dest.writeString(code_day);dest.writeString(text_night);dest.writeString(code_night);dest.writeString(high);dest.writeString(low);dest.writeString(precip);dest.writeString(wind_direction);dest.writeString(wind_direction_degree);dest.writeString(wind_speed);dest.writeString(wind_scale);}@Overridepublic String toString() {return "Weather{" +"date='" + date + '\'' +", text_day='" + text_day + '\'' +", code_day='" + code_day + '\'' +", text_night='" + text_night + '\'' +", code_night='" + code_night + '\'' +", high='" + high + '\'' +", low='" + low + '\'' +", precip='" + precip + '\'' +", wind_direction='" + wind_direction + '\'' +", wind_direction_degree='" + wind_direction_degree + '\'' +", wind_speed='" + wind_speed + '\'' +", wind_scale='" + wind_scale + '\'' +'}';}
}
**fragment文件**
HomeFragment
public class HomeFragment extends Fragment {private PagerSlidingTabStrip pst;private ViewPager vp;private List<Fragment> fragmentList;private List<Map<String, String>> channelList;private List<String> titles;private NewsFragmentAdapter nfa;public HomeFragment() {// Required empty public constructor}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.home_layout, container, false);}@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);fragmentList = new ArrayList<>();titles = new ArrayList<>();pst = (PagerSlidingTabStrip) getView().findViewById(R.id.pst);vp = (ViewPager) getView().findViewById(R.id.vp);nfa = new NewsFragmentAdapter(getChildFragmentManager(), fragmentList, titles);vp.setAdapter(nfa);vp.setOffscreenPageLimit(2);pst.setViewPager(vp);pst.setIndicatorHeight(0);pst.setUnderlineHeight(0);pst.setShouldExpand(true);//读取文件 文件名String fileName = "channel.txt";//获得文件所在的包名String pn = getActivity().getPackageName();//如果存在频道文件则读取 否则 从网络获取if (FileUitlity.fileExists(pn + "/" + fileName)) {String ja = FileUitlity.readFileFromSdcard(pn + "/" + fileName);try {Log.d("=====", "读取文件成功");Log.d("====1=", ja);initFragment(new JSONArray(ja));} catch (JSONException e) {e.printStackTrace();}} else {new GetChannel().execute(UrlUtil.channelUrl);}}//获取频道的异步任务类public class GetChannel extends AsyncTask<String, Void, String> {@Overrideprotected String doInBackground(String... strings) {return HttpUtil.HttpGet(strings[0]);}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);//解析频道json数据try {JSONObject jsonObject = new JSONObject(s);JSONObject body = jsonObject.getJSONObject("showapi_res_body");JSONArray ja = body.getJSONArray("channelList");if (ja.length() > 0) {String pn = getActivity().getPackageName();FileUitlity.getInstance(getActivity(), pn);String result = FileUitlity.saveFileToSdcard(pn + "/channel.txt",ja.toString());if (result.equals("ok")) {Log.d("=====", "文件保存成功");} else {Log.d("=====", "文件保存失败");}}initFragment(ja);} catch (JSONException e) {e.printStackTrace();}}}//初始化fragmentpublic void initFragment(JSONArray ja) throws JSONException {//解析完频道数据后 放入channelList中channelList = new ArrayList<>();for (int i = 0; i < ja.length(); i++) {JSONObject obj = (JSONObject) ja.get(i);String id = obj.getString("channelId");String name = obj.getString("name");HashMap map = new HashMap();map.put("id", id);map.put("name", name);channelList.add(map);titles.add(name);}//根据频道数新建fragmentfor (int i = 0; i < channelList.size(); i++) {Fragment fragment = new NewsFragment();Bundle bundle = new Bundle();//获取频道的id和name 并把他们传到NewsFragment中去bundle.putString("id", channelList.get(i).get("id"));bundle.putString("name", channelList.get(i).get("name"));//把频道的id和name放入相应的fragment中去fragment.setArguments(bundle);fragmentList.add(fragment);}pst.notifyDataSetChanged();nfa.notifyDataSetChanged();}
}
NewsFragment
public class NewsFragment extends Fragment {private PullToRefreshListView prlv;private NewsBaseAdapter nba;private List<MyNews> newsList;private NewsCacheDao newsCacheDao;private String url;private TextView tv;private int page = 1;private String id, name;//Handler要用OS包里的 Handler的声明方式不同 大括号后面要加分号private Handler handler = new Handler() {//handleMessag在主线程中运行 相当于异步任务类里的OnPostExcute()@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);//判断属于哪个线程进行实现if (msg.what == 1) {Bundle bundle = msg.getData();List list = bundle.getParcelableArrayList("cache");newsList.addAll(list);nba.notifyDataSetChanged();//tv.setText("读取缓存成功");new GetNews().execute(url);}}};public NewsFragment() {// Required empty public constructor}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.fragment_news, container, false);}@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);newsCacheDao = new NewsCacheDao(getActivity());newsList = new ArrayList<>();tv = (TextView) getView().findViewById(R.id.tv);prlv = (PullToRefreshListView) getView().findViewById(R.id.prlv);nba = new NewsBaseAdapter(newsList,getActivity());prlv.setAdapter(nba);//设置上下都可以刷新prlv.setMode(PullToRefreshBase.Mode.BOTH);//注册监听prlv.setOnRefreshListener(new prlvLisen());Bundle bundle = getArguments();//接收HomeFragment中传过来的数据 这样才能知道现在处于哪个频道下 然后根据频道的id和name加载不同的数据id = bundle.getString("id");name = bundle.getString("name");url = UrlUtil.newsUrl + "?channelId=" + id+ "&channelName=" + name + "&needHtml=1";//执行线程要用run//new GetCache(id).run();new Thread(new GetCache()).start();//getCache(id);//new GetNews().execute(url);(这一句转去 getCache里写)}//读取数据库缓存 线程public class GetCache implements Runnable {//run()在子线程中运行@Overridepublic void run() {Bundle bundle = new Bundle();ArrayList<MyNews> list = newsCacheDao.searchNews(id);bundle.putParcelableArrayList("cache", list);//tv.setText("读取缓存成功");//nba.notifyDataSetChanged();//new GetNews().execute(url);Message message = new Message();//如果有需要的话先把数据放入bundle里 再放入message里//message.setData();message.setData(bundle);message.what = 1;//告诉它子线程已经执行完了 要返回子线程中去handler.sendMessage()handler.sendMessage(message);}}//加载网络数据 异步任务类public class GetNews extends AsyncTask<String, Void, String> {@Overrideprotected String doInBackground(String... strings) {return HttpUtil.HttpGet(strings[0]);}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);//解析 新闻数据try {JSONObject obj = new JSONObject(s);JSONObject body = obj.getJSONObject("showapi_res_body");JSONObject pageBean = body.getJSONObject("pagebean");JSONArray contentList = pageBean.getJSONArray("contentlist");if (page == 1) {newsList.clear();}//在获取网络的时候清空list(防止重复) 不是清空数据库for (int i = 0; i < contentList.length(); i++) {JSONObject jo = (JSONObject) contentList.get(i);//MyNews要有一个空的构造 不然这句话报错MyNews myNews = new MyNews();myNews.setTitle(jo.getString("title"));myNews.setPubDate(jo.getString("pubDate"));myNews.setImageurls(jo.getString("imageurls"));myNews.setSource(jo.getString("source"));myNews.setHtml(jo.getString("html"));myNews.setChannelId(jo.getString("channelId"));newsCacheDao.addNews(myNews);newsList.add(myNews);}nba.notifyDataSetChanged();prlv.onRefreshComplete();} catch (JSONException e) {e.printStackTrace();}}}// public void getCache(String id) {// //读本地缓存
// newsList.addAll(newsCacheDao.searchNews(id));
// nba.notifyDataSetChanged();
// //如果没有加载网络
// if (newsList.size() == 0) {// new GetNews().execute(url);
// }
// }//下拉上拉 监听 内部类public class prlvLisen implements PullToRefreshBase.OnRefreshListener2 {@Overridepublic void onPullDownToRefresh(PullToRefreshBase refreshView) {page = 1;url = UrlUtil.newsUrl + "?channelId=" + id+ "&channelName=" + name + "&page=" + page + "&needHtml=1";new GetNews().execute(url);}@Overridepublic void onPullUpToRefresh(PullToRefreshBase refreshView) {page++;url = UrlUtil.newsUrl + "?channelId=" + id+ "&channelName=" + name + "&page=" + page + "&needHtml=1";new GetNews().execute(url);}}
MyFragment
public class MyFragment extends Fragment {private KenBurnsView img;private ImageView collection;public MyFragment() {// Required empty public constructor}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.my_layout, container, false);}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);img= (KenBurnsView) getView().findViewById(R.id.img);collection= (ImageView) getView().findViewById(R.id.collection);collection.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent(getActivity(), CollectionActivity.class);startActivity(intent);}});}
TopicFragment(里面为天气)
public class TopicFragment extends Fragment {private RequestQueue queue;private SwipeRefreshLayout swip;private CardView card1, card2, card3;private WeatherCacheDao weatherCacheDao;public TopicFragment() {// Required empty public constructor}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.weather_layout, container, false);}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);card1 = (CardView) getView().findViewById(R.id.card1);card2 = (CardView) getView().findViewById(R.id.card2);card3 = (CardView) getView().findViewById(R.id.card3);weatherCacheDao = new WeatherCacheDao(getActivity());queue = Volley.newRequestQueue(getActivity());swip = (SwipeRefreshLayout) getView().findViewById(R.id.swip);//进度条背景色swip.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorPrimary));swip.setColorSchemeResources(R.color.colorAccent);swip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {@Override//下拉刷新时执行此方法 可以写加载网络。。。等命令public void onRefresh() {//.......//收起刷新进度条//swip.setRefreshing(false);//new Thread(new GetCache()).start();getWeather();}});readDatabase();}public void readDatabase() {List<Weather> list = weatherCacheDao.searchWeather();//去生成Weather的toString方法paraseList(list);}//获取天气public void getWeather() {String url = UrlUtil.weatherUrl + "?location=yantai";StringGetRequest sgr = new StringGetRequest(Request.Method.GET, url, newResponse.Listener<String>() {@Overridepublic void onResponse(String s) {if (!s.equals("")) {try {JSONObject obj = new JSONObject(s);JSONArray results = obj.getJSONArray("results");JSONArray ja1 = ((JSONObject) (results.get(0))).getJSONArray("daily");Gson gson = new Gson();List<Weather> list = gson.fromJson(ja1.toString(), new TypeToken<List<Weather>>() {}.getType());//只要一刷新就把缓存的清空掉weatherCacheDao.deleteAll();paraseList(list);// for (int i = 0; i < results.length(); i++) {// JSONObject jo = results.getJSONObject(i);
// Weather weather = new Weather();
// weather.setDate(jo.getString("date"));
// weather.setText_day(jo.getString("text_day"));
// weather.setCode_day(jo.getString("code_day"));
// weather.setText_night(jo.getString("text_night"));
// weather.setCode_night(jo.getString("code_nigh"));
// weather.setHigh(jo.getString("high"));
// weather.setLow(jo.getString("low"));
// weather.setPrecip(jo.getString("precip"));
// weather.setWind_direction(jo.getString("wind_direction"));
// weather.setWind_direction_degree(jo.getString("wind_direction_degree"));
// weather.setWind_speed(jo.getString("wind_speed"));
// weather.setWind_scale(jo.getString("wind_scale"));
// weatherList.add(weather);
// }} catch (JSONException e) {e.printStackTrace();}}swip.setRefreshing(false);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError volleyError) {swip.setRefreshing(false);}});sgr.putHeaders("apikey", "3f37b44e3115841957414d7c4bf6c0f5");queue.add(sgr);}//解析weatherpublic void paraseList(List<Weather> list) {for (int i = 0; i < list.size(); i++) {View view = LayoutInflater.from(getActivity()).inflate(R.layout.weather_content, null);Weather day = list.get(i);weatherCacheDao.addWeather(day);TextView date = (TextView) view.findViewById(R.id.date);TextView text_day = (TextView) view.findViewById(R.id.text_day);TextView code_day = (TextView) view.findViewById(R.id.code_day);TextView text_night = (TextView) view.findViewById(R.id.text_night);TextView code_night = (TextView) view.findViewById(R.id.code_night);TextView high = (TextView) view.findViewById(R.id.high);TextView low = (TextView) view.findViewById(R.id.low);TextView precip = (TextView) view.findViewById(R.id.precip);TextView wind_direction = (TextView) view.findViewById(R.id.wind_direction);TextView wind_direction_degree = (TextView) view.findViewById(R.id.wind_direction_degree);TextView wind_speed = (TextView) view.findViewById(R.id.wind_speed);TextView wind_scale = (TextView) view.findViewById(R.id.wind_scale);date.setText(day.getDate());text_day.setText(day.getText_day());code_day.setText(day.getCode_day());text_night.setText(day.getText_night());code_night.setText(day.getCode_night());high.setText(day.getHigh());low.setText(day.getLow());precip.setText(day.getPrecip());wind_direction.setText(day.getWind_direction());wind_direction_degree.setText(day.getWind_direction_degree());wind_scale.setText(day.getWind_scale());wind_speed.setText(day.getWind_speed());if (i == 0) {if (card1.getChildCount() > 0) {card1.removeAllViews();}card1.addView(view);}if (i == 1) {if (card2.getChildCount() > 0) {card2.removeAllViews();}card2.addView(view);}if (i == 2) {if (card3.getChildCount() > 0) {card3.removeAllViews();}card3.addView(view);}}}
}
**util工具类**
public class HttpUtil {public static String HttpGet(String uri){HttpURLConnection con = null;BufferedReader reader = null;InputStream is = null;StringBuilder sbd = new StringBuilder();try {URL url = new URL(uri);con = (HttpURLConnection) url.openConnection();con.setConnectTimeout(5*1000);con.setReadTimeout(5*1000);con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");con.connect();if(con.getResponseCode()==200){is = con.getInputStream();reader = new BufferedReader(new InputStreamReader(is));String strRead = null;while ((strRead = reader.readLine()) != null) {sbd.append(strRead);sbd.append("\r\n");}return sbd.toString();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(reader!=null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return "";}}
public class FileUitlity {private static String ROOT_CACHE;private static FileUitlity instance = null;private FileUitlity() {}//创建文件夹public static FileUitlity getInstance(Context context, String root_dir) {if (instance == null) {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"+ root_dir + "/");} else {ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/" + root_dir + "/");}File dir = new File(ROOT_CACHE);if (!dir.exists()) {dir.mkdirs();}instance = new FileUitlity();}return instance;}public File makeDir(String dir) {File fileDir = new File(ROOT_CACHE + dir);if (fileDir.exists()) {return fileDir;} else {fileDir.mkdirs();return fileDir;}}//判断文件是否存在SD卡public static boolean fileExists(String fileName) {String state = Environment.getExternalStorageState();if (!state.equals(Environment.MEDIA_MOUNTED)) {return false;} else {File root = Environment.getExternalStorageDirectory();File file = new File(root, fileName);return file.exists();}}//保存文件到SD卡public static String saveFileToSdcard(String fileName, String content) {String state = Environment.getExternalStorageState();if (!state.equals(Environment.MEDIA_MOUNTED)) {return "SD卡未就绪";}File root = Environment.getExternalStorageDirectory();FileOutputStream fos = null;try {fos = new FileOutputStream(root + "/" + fileName);fos.write(content.getBytes());return "ok";} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}return "";}//读取SD卡文件public static String readFileFromSdcard(String fileName) {String statue = Environment.getExternalStorageState();if (!statue.equals(Environment.MEDIA_MOUNTED)) {return "";} else {File root = Environment.getExternalStorageDirectory();BufferedReader reader = null;FileInputStream fis = null;StringBuilder sbd = new StringBuilder();try {fis = new FileInputStream(root + "/" + fileName);reader = new BufferedReader(new InputStreamReader(fis));String row = "";while ((row = reader.readLine()) != null) {sbd.append(row);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return sbd.toString();}}
}
public class StringGetRequest extends StringRequest {private Map<String, String> header;public StringGetRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {super(method, url, listener, errorListener);header = new HashMap<>();}public void putHeaders(String key, String value) {header.put(key, value);}public Map<String, String> getHeaders() throws AuthFailureError {return header;}}
public class StringPostRequest extends StringRequest {private Map<String, String> params;private Map<String, String> header;public StringPostRequest(String url, Listener<String> listener,ErrorListener errorListener) {//super实际调用了StringRequest的四参构造super(Method.POST, url, listener, errorListener);params = new HashMap<String, String>();header = new HashMap<String, String>();}@Override//回调方法 用的时候往Map里放值就可以protected Map<String, String> getParams() throws AuthFailureError {return params;}public void putParams(String key, String value) {this.params.put(key, value);}public Map<String, String> getHeaders() throws AuthFailureError {return header;}public void putHeaders(String key, String value) {this.header.put(key, value);}
}
public class UrlUtil {//获取频道的网络接口public static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";/*/获取频道对应新闻的网络接口get请求参数:channelId :新闻频道id,必须精确匹配channelName :新闻频道名称,可模糊匹配title :新闻标题,模糊匹配page :页数,默认1。每页最多20条记needContent:是否需要返回正文,1为需要needHtml:是否需要返回正文的html格式,1为需要*///获取新闻的网络接口public static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";/*参数名 类型 必填 参数位置 描述 默认值location string 是 urlParam 所查询的位置 beijinglanguage string 否 urlParam 语言 zh-Hansunit string 否 urlParam 单位 cstart string 否 urlParam 起始时间 0days string 否 urlParam 天数 3*///获取天气的网络接口public static String weatherUrl = "http://apis.baidu.com/thinkpage/weather_api/suggestion";
}
public class PhotoViewPager extends ViewPager
{private float mTrans;private float mScale;/*** 最大的缩小比例*/private static final float SCALE_MAX = 0.0f;/*** 保存position与对于的View*/private HashMap<Integer, View> mChildrenViews = new LinkedHashMap<Integer, View>();/*** 滑动时左边的元素*/private View mLeft;/*** 滑动时右边的元素*/private View mRight;public PhotoViewPager(Context context, AttributeSet attrs){super(context, attrs);}@Overridepublic void onPageScrolled(int position, float positionOffset,int positionOffsetPixels){// Log.e(TAG, "position=" + position+", positionOffset = "+positionOffset+" ,positionOffsetPixels = " + positionOffsetPixels+" , currentPos = " + getCurrentItem());//滑动特别小的距离时,我们认为没有动,可有可无的判断float effectOffset = isSmall(positionOffset) ? 0 : positionOffset;//获取左边的ViewmLeft = findViewFromObject(position);//获取右边的ViewmRight = findViewFromObject(position + 1);// 添加切换动画效果animateStack(mLeft, mRight, effectOffset, positionOffsetPixels);super.onPageScrolled(position, positionOffset, positionOffsetPixels);}public void setObjectForPosition(View view, int position){mChildrenViews.put(position, view);}/*** 通过过位置获得对应的View* * @param position* @return*/public View findViewFromObject(int position){return mChildrenViews.get(position);}private boolean isSmall(float positionOffset){return Math.abs(positionOffset) < 0.0001;}protected void animateStack(View left, View right, float effectOffset,int positionOffsetPixels){if (right != null){/*** 缩小比例 如果手指从右到左的滑动(切换到后一个):0.0~1.0,即从一半到最大* 如果手指从左到右的滑动(切换到前一个):1.0~0,即从最大到一半*/mScale = (1 - SCALE_MAX) * effectOffset + SCALE_MAX;/*** x偏移量: 如果手指从右到左的滑动(切换到后一个):0-720 如果手指从左到右的滑动(切换到前一个):720-0*/mTrans = -getWidth() - getPageMargin() + positionOffsetPixels;right.setScaleX(mScale);right.setScaleY(mScale);right.setTranslationX(mTrans);}if (left != null){left.bringToFront();}}@Overridepublic boolean onTouchEvent(MotionEvent ev) {try {return super.onTouchEvent(ev);} catch (IllegalArgumentException ex) {ex.printStackTrace();}return false;}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {try {return super.onInterceptTouchEvent(ev);} catch (IllegalArgumentException ex) {ex.printStackTrace();}return false;}
}
**布局文件**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.edu.jereh.mynews.MainActivity"><FrameLayout
android:id="@+id/fl"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"></FrameLayout><android.support.v4.app.FragmentTabHost
android:id="@+id/ft"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="#f7f0f0"></android.support.v4.app.FragmentTabHost></LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.edu.jereh.mynews.ContentActivity"><LinearLayout
android:id="@+id/linearLayout"android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><ImageView
android:id="@+id/back"android:layout_width="30dp"android:layout_height="match_parent"android:layout_weight="0.1"android:src="@mipmap/back" /><TextView
android:id="@+id/title"android:layout_width="wrap_content"android:layout_height="match_parent"android:background="@color/webViewTopBg"android:gravity="center"android:text="AAA"android:layout_weight="1"android:textSize="15sp"android:textStyle="bold" /><TextView
android:id="@+id/collection"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center"android:layout_weight="1"android:text="收藏" /></LinearLayout><WebView
android:id="@+id/wv"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_below="@+id/linearLayout"></WebView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.edu.jereh.mynews.CollectionActivity">
<ListView
android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/lv"></ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.edu.jereh.mynews.ImgActivity">
<com.edu.jereh.mynews.view.PhotoViewPagerandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/pvp">
</com.edu.jereh.mynews.view.PhotoViewPager>
</RelativeLayout
<?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"android:orientation="vertical"android:weightSum="1"><TextView
android:id="@+id/title"android:layout_marginTop="5dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:text="标题" /><LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:id="@+id/source"android:layout_width="match_parent"android:layout_height="50dp"android:text="新浪"android:layout_weight="1"android:gravity="center"android:layout_above="@+id/content"android:layout_toEndOf="@+id/img" /><TextView
android:id="@+id/pubDate"android:layout_width="match_parent"android:layout_height="50dp"android:text="刚刚"android:layout_weight="1"android:gravity="center"android:layout_alignBottom="@+id/content" />
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:weightSum="1"><TextView
android:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center"android:text="标题"android:layout_marginTop="5dp"android:layout_alignEnd="@+id/pubDate"android:layout_toEndOf="@+id/img"android:layout_alignParentTop="true" /><ImageView
android:id="@+id/img"android:layout_width="100dp"android:layout_height="100dp"android:src="@mipmap/ic_launcher"android:layout_alignParentTop="true"android:layout_alignParentStart="true" /><TextView
android:id="@+id/source"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="新浪"android:layout_alignBottom="@+id/img"android:layout_centerHorizontal="true" /><TextView
android:id="@+id/pubDate"android:layout_width="wrap_content"android:layout_height="50dp"android:text="刚刚"android:layout_alignTop="@+id/source"android:layout_alignParentEnd="true"android:layout_alignBottom="@+id/source" />
</RelativeLayout>
<?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"android:orientation="vertical"android:weightSum="1"><TextView
android:id="@+id/title"android:layout_marginTop="5dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:text="标题" />
<LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/ll1"android:orientation="horizontal"><ImageView
android:layout_width="90dp"android:layout_height="90dp"android:layout_weight="1"android:id="@+id/img"android:src="@mipmap/ic_launcher"/><ImageView
android:layout_width="90dp"android:layout_height="90dp"android:id="@+id/img2"android:layout_weight="1"android:src="@mipmap/ic_launcher"/></LinearLayout><LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/ll2"android:orientation="horizontal"><TextView
android:id="@+id/source"android:layout_width="match_parent"android:layout_height="50dp"android:text="新浪"android:layout_weight="1"android:gravity="center"android:layout_above="@+id/content"android:layout_toEndOf="@+id/img" /><TextView
android:id="@+id/pubDate"android:layout_width="match_parent"android:layout_height="50dp"android:text="刚刚"android:layout_weight="1"android:gravity="center"android:layout_alignBottom="@+id/content" />
</LinearLayout>
</LinearLayout>
<?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"android:orientation="vertical"android:weightSum="1"><TextView
android:id="@+id/title"android:layout_marginTop="5dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:text="标题" />
<LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/ll1"android:orientation="horizontal"><ImageView
android:layout_width="90dp"android:layout_height="90dp"android:id="@+id/img"android:layout_weight="1"android:src="@mipmap/ic_launcher"/><ImageView
android:layout_width="90dp"android:layout_height="90dp"android:id="@+id/img2"android:layout_weight="1"android:src="@mipmap/ic_launcher"/><ImageView
android:layout_width="90dp"android:layout_height="90dp"android:id="@+id/img3"android:layout_weight="1"android:src="@mipmap/ic_launcher"/></LinearLayout><LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/ll2"android:orientation="horizontal"><TextView
android:id="@+id/source"android:layout_width="match_parent"android:layout_height="50dp"android:text="新浪"android:layout_weight="1"android:gravity="center"android:layout_above="@+id/content"android:layout_toEndOf="@+id/img" /><TextView
android:id="@+id/pubDate"android:layout_width="match_parent"android:layout_height="50dp"android:text="刚刚"android:layout_weight="1"android:gravity="center"android:layout_alignBottom="@+id/content" />
</LinearLayout>
</LinearLayout>
<?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"android:orientation="vertical"><TextView
android:id="@+id/date"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_marginTop="10dp"android:gravity="center"android:textSize="18sp"android:textStyle="bold" /><LinearLayout
android:id="@+id/ll1"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:id="@+id/text_day"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /><TextView
android:id="@+id/code_day"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll2"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:id="@+id/text_night"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /><TextView
android:id="@+id/code_night"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll3"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="最高气温:"android:textSize="14sp" /><TextView
android:id="@+id/high"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll4"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="最低气温:"android:textSize="14sp" /><TextView
android:id="@+id/low"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll5"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="降水概率:"android:textSize="14sp" /><TextView
android:id="@+id/precip"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll6"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:id="@+id/wind_direction"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /><TextView
android:id="@+id/wind_direction_degree"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll7"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="风速为:"android:textSize="14sp" /><TextView
android:id="@+id/wind_speed"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout><LinearLayout
android:id="@+id/ll8"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="风力等级:"android:textSize="14sp" /><TextView
android:id="@+id/wind_scale"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:textSize="14sp" /></LinearLayout></LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/swip"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><android.support.v7.widget.CardViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="30dp"android:layout_weight="1"android:layout_margin="5dp"app:cardCornerRadius="10dp"app:cardElevation="10dp"app:contentPadding="10dp"app:cardBackgroundColor="#98e79a"android:clickable="true"android:foreground="?android:selectableItemBackground"android:id="@+id/card1"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="今日天气"/></android.support.v7.widget.CardView><android.support.v7.widget.CardViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="30dp"android:layout_weight="1"android:layout_margin="5dp"app:cardCornerRadius="10dp"app:cardElevation="10dp"app:contentPadding="10dp"app:cardBackgroundColor="#7897ed"android:clickable="true"android:foreground="?android:selectableItemBackground"android:id="@+id/card2"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="明日天气"/></android.support.v7.widget.CardView><android.support.v7.widget.CardViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="30dp"android:layout_weight="1"android:layout_margin="5dp"app:cardCornerRadius="10dp"app:cardElevation="10dp"app:contentPadding="10dp"app:cardBackgroundColor="#f5f562"android:clickable="true"android:foreground="?android:selectableItemBackground"android:id="@+id/card3"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="后日天气"/></android.support.v7.widget.CardView></LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>
运行效果展示:
显示收藏的新闻:
AndroidStudio——今日头条(可以实时获取数据的app)相关推荐
- android studio今日头条,AndroidStudio——今日头条(可以实时获取数据的app)
今日头条包含以下模块: 首页 视频 天气 和 我的 其中 首页用于加载实时的新闻频道及内容,可以实现点击图片查看图片详情,并且可以实现内容的收藏与取消收藏 视频模块暂时未加入任何内容 天气模块可以实现 ...
- 前端学习(3049):vue+element今日头条管理-请求获取数据
- 今日头条页面图片获取
今日头条页面图片获取 分为获取目录下的文件路径 以及具体目录下的多张图片 import re import requests import json,os from urllib import req ...
- qtableview点击行将整行数据传过去_可以实时获取数据的Database Asset插件
前言:Goby之前开放的插件入口点较少,大家只能在扫描前.扫描后执行事件,无法参与扫描过程中来.为实现更多场景的应用及提高扫描效率(如:后台爆破子域名等),Goby开放了一些新的API:事件通知机制. ...
- 成年人才是走失比例最高的!今日头条发布走失人口数据报告
7月24日消息,今日头条副总编辑徐一龙根据三年间7万余条寻人线索总结发布了"走失人口数据报告",报告总结得出了"72小时是走失者回家的黄金时间".近一半走失老人 ...
- 简单爬今日头条街拍获取图集
emmmmmm这次练手真的是一波三折-不是爬了半天发现是静态网页就是网页重要内容被隐藏要么就是网页参数的内容进行了加密-最后终于找到了头条街拍可以爬,前面都很顺利-然而本来想要获取每一张图片的url的 ...
- 今日头条2018校招大数据/算法方向(第一批)详解
问答题 1.给定一棵树的根节点, 在已知该树最大深度的情况下, 求节点数最多的那一层并返回具体的层数. 如果最后答案有多层, 输出最浅的那一层,树的深度不会超过100000.实现代码如下,请指出代码中 ...
- python新闻评论分析_今日头条新闻评论获取
*为什么有这篇文章 因为老婆博士专业的原因,她需要获取不少网站的新闻或者帖子的评论,并且对评论进行数据分析或者是自然语义分析(NLP).因此从来没有接触过 python,只有 VB 二级的我自然就成了 ...
- ajax前端实时获取数据
<script type="text/javascript"> // getImgs() 函数中写ajax请求就可以var taskTimer = null;taskT ...
最新文章
- 另辟蹊径,中科院自动化所等首次用图卷积网络解决语义分割难题
- 麦块我的世界怎么用java_麦块我的世界怎么玩啊?
- SwipeRefreshLayout实现上拉加载
- 【Linux】30.ssh不用手动输入密码登录终端sshpass 和 shell脚本后跟参数自动匹配case的用法
- 如何轻松记忆Linux文件系统层次结构
- 解决undefined reference to symbol ‘sem_close@@GLIBC_2.2.5‘问题
- 怎么编写java_程序员学编程第一步:手把手教你开发第一个Java程序
- DataGridView使用方法汇总
- Windows server WSUS补丁服务器搭建(转)
- Canvas--文字渲染
- Oracle 备份shell,oracle数据库shell备份脚本
- ElasticSearch常用的几种查询方式
- apipost如何使用mock测试
- 【Ubantu】Ubantu 20.04设置root账户密码,查看共享文件夹
- 一天2篇Nature!任职同一高校,这对教授夫妻同时发表2项医学新成果
- 阿里云产品推荐——专有网络 VPC
- 学Python运维,这知识点你肯定会遇到,【必收藏之】nginx 域名跳转相关配置
- 中冠百年|怎样才能提高个人理财的执行力
- flex effect
- linux网络协议栈(四)链路层 (5)vlan处理