Android#15 -- MyDay App (1)
2017-10-19 本文已影响0人
喜欢书的女孩
文章目录
一、 项目架构
功能模块
原型设计
架构设计
代码编写
测试
二、团队分工
[1] 功能模块
设想的功能模块图
[2]原型设计
开始页
天气
穿搭
日程
个人
[3]架构设计
架构设计
[4]代码编写
- 整体管理类
- AppManager ---activity 管理类
public class AppManager {
private static Stack<Activity> activityStack;
private volatile static AppManager instance;
private AppManager() {
}
/**
* 单一实例
*/
public static AppManager getAppManager() {
if (instance == null) {
synchronized (AppManager.class){
if(instance==null){
instance = new AppManager();
instance.activityStack = new Stack();
}
}
}
return instance;
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<Activity>();
}
activityStack.add(activity);
}
/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
try {
Activity activity = activityStack.lastElement();
return activity;
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
/**
* 获取当前Activity的前一个Activity
*/
public Activity preActivity() {
int index = activityStack.size() - 2;
if (index < 0) {
return null;
}
Activity activity = activityStack.get(index);
return activity;
}
/**
* 结束当前Activity(堆栈中最后一个压入的)
*/
public void finishActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
activity = null;
}
}
/**
* 移除指定的Activity
*/
public void removeActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity = null;
}
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
try {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
/**
* 返回到指定的activity
*
* @param cls
*/
public void returnToActivity(Class<?> cls) {
while (activityStack.size() != 0)
if (activityStack.peek().getClass() == cls) {
break;
} else {
finishActivity(activityStack.peek());
}
}
/**
* 是否已经打开指定的activity
* @param cls
* @return
*/
public boolean isOpenActivity(Class<?> cls) {
if (activityStack!=null){
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (cls == activityStack.peek().getClass()) {
return true;
}
}
}
return false;
}
/**
* 退出应用程序
*
* @param context 上下文
* @param isBackground 是否开开启后台运行
*/
public void AppExit(Context context, Boolean isBackground) {
try {
finishAllActivity();
ActivityManager activityMgr = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
activityMgr.restartPackage(context.getPackageName());
} catch (Exception e) {
} finally {
// 注意,如果您有后台程序运行,请不要支持此句子
if (!isBackground) {
System.exit(0);
}
}
}
}
- BaseActivity ---activity的基类
public abstract class BaseActivity extends AppCompatActivity{
public Context mContext;
private Unbinder mUnbinder;
private int count;//记录开启进度条的情况 只能开一个
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
doBeforeSetcontentView();
setContentView(getLayoutId());
// 默认着色状态栏
SetStatusBarColor();
mUnbinder = ButterKnife.bind(this);
mContext = this;
this.initPresenter();
this.initView();
}
/**
* 设置layout前配置
*/
private void doBeforeSetcontentView() {
// 把actvity放到application栈中管理
AppManager.getAppManager().addActivity(this);
// 无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 设置竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/*********************
* 子类实现
*****************************/
//获取布局文件
public abstract int getLayoutId();
//简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
public abstract void initPresenter();
//初始化view
public abstract void initView();
/**
* 着色状态栏(4.4以上系统有效)
*/
protected void SetStatusBarColor() {
StatusBarSetting.setColor(this, getResources().getColor(R.color.colorPrimary));
}
/**
* 着色状态栏(4.4以上系统有效)
*/
protected void SetStatusBarColor(int color) {
StatusBarSetting.setColor(this, color);
}
/**
* 沉浸状态栏(4.4以上系统有效)
*/
protected void SetTranslanteBar() {
StatusBarSetting.setTranslucent(this);
}
/**
* 通过Class跳转界面
**/
public void startActivity(Class<?> cls) {
startActivity(cls, null);
}
/**
* 通过Class跳转界面
**/
public void startActivityForResult(Class<?> cls, int requestCode) {
startActivityForResult(cls, null, requestCode);
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivityForResult(Class<?> cls, Bundle bundle,
int requestCode) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivity(Class<?> cls, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* 开启浮动加载进度条
*/
public void startProgressDialog() {
count++;
if(count==1){
// LoadingDialog.showDialogForLoading(this);
}
}
/**
* 开启浮动加载进度条
*
* @param msg
*/
public void startProgressDialog(String msg) {
count++;
if(count==1){
//LoadingDialog.showDialogForLoading(this, msg, true);
}
}
/**
* 停止浮动加载进度条
*/
public void stopProgressDialog() {
count--;
if(count==0){
// LoadingDialog.cancelDialogForLoading();
}
}
/**
* 短暂显示Toast提示(来自String)
**/
public void showShortToast(String text) {
ToastUitl.showShort(text);
}
/**
* 短暂显示Toast提示(id)
**/
public void showShortToast(int resId) {
ToastUitl.showShort(resId);
}
/**
* 长时间显示Toast提示(来自res)
**/
public void showLongToast(int resId) {
ToastUitl.showLong(resId);
}
/**
* 长时间显示Toast提示(来自String)
**/
public void showLongToast(String text) {
ToastUitl.showLong(text);
}
/**
* 带图片的toast
*
* @param text
* @param res
*/
public void showToastWithImg(String text, int res) {
ToastUitl.showToastWithImg(text, res);
}
/**
* 网络访问错误提醒
*/
public void showNetErrorTip() {
ToastUitl.showToastWithImg(getText(R.string.net_error).toString(), R.drawable.ic_wifi_off);
}
public void showNetErrorTip(String error) {
ToastUitl.showToastWithImg(error, R.drawable.ic_wifi_off);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mUnbinder.unbind();
AppManager.getAppManager().finishActivity(this);
}
}
- BaseFragmentAdapter ---fragment的处理
public class BaseFragmentAdapter extends FragmentPagerAdapter{
List<Fragment> fragmentList = new ArrayList<Fragment>();
private List<String> mTitles;
public BaseFragmentAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
public BaseFragmentAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> mTitles) {
super(fm);
this.fragmentList = fragmentList;
this.mTitles = mTitles;
}
@Override
public CharSequence getPageTitle(int position) {
return !CollectionUtils.isNullOrEmpty(mTitles) ? mTitles.get(position) : "";
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
- 工具类
- HttpUtils
/**
* 获取服务器数据
*/
public void getWeather(){
// String showapi_appid="48138";//要替换成自己的
// String showapi_sign="ede742069d024875a86520572b742c17";//要替换成自己的
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.POST, "http://route.showapi.com/9-2", new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.e("TAG", "onResponse: "+ s );
jsonParser(s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", "onErrorResponse: 错误" +error.toString());
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap();
map.put("showapi_appid","48138");
map.put("showapi_sign","ede742069d024875a86520572b742c17");
map.put("area", "广州");
return map;
}
};
queue.add(request);
}
- ParseDateUtils
//[4]解析数据
private void jsonParser(String jsonData) {
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject body = jsonObject.getJSONObject("showapi_res_body");
// time=body.getString("time");
// Log.i(TAG,"时间"+time);
JSONObject now = body.getJSONObject("now");
weather=now.optString("weather","defaultValue");
temperature=now.optString("temperature","defaultValue");
wind_power=now.optString("wind_power","defaultValue");
temperature_time = now.optString("temperature_time","defaultValue");
Log.i(TAG,"天气"+weather);
Log.i(TAG,"温度"+temperature);
Log.i(TAG,"风力"+wind_power);
Log.i(TAG,"时刻"+temperature_time);
} catch (JSONException e) {
e.printStackTrace();
}
}
- ToastUitl
public class ToastUitl {
private static Toast toast;
private static Toast toast2;
private static Toast initToast(CharSequence message, int duration) {
if (toast == null) {
toast = Toast.makeText(BaseApplication.getAppContext(), message, duration);
} else {
toast.setText(message);
toast.setDuration(duration);
}
return toast;
}
/**
* 短时间显示Toast
*
* @param message
*/
public static void showShort(CharSequence message) {
initToast(message, Toast.LENGTH_SHORT).show();
}
/**
* 短时间显示Toast
*
* @param strResId
*/
public static void showShort(int strResId) {
// Toast.makeText(context, strResId, Toast.LENGTH_SHORT).show();
initToast(BaseApplication.getAppContext().getResources().getText(strResId), Toast.LENGTH_SHORT).show();
}
/**
* 长时间显示Toast
*
* @param message
*/
public static void showLong(CharSequence message) {
initToast(message, Toast.LENGTH_LONG).show();
}
/**
* 长时间显示Toast
*
* @param strResId
*/
public static void showLong(int strResId) {
initToast(BaseApplication.getAppContext().getResources().getText(strResId), Toast.LENGTH_LONG).show();
}
/**
* 自定义显示Toast时间
*
* @param message
* @param duration
*/
public static void show(CharSequence message, int duration) {
initToast(message, duration).show();
}
/**
* 自定义显示Toast时间
*
* @param context
* @param strResId
* @param duration
*/
public static void show(Context context, int strResId, int duration) {
initToast(context.getResources().getText(strResId), duration).show();
}
/**
* 显示有image的toast
*
* @param tvStr
* @param imageResource
* @return
*/
public static Toast showToastWithImg(final String tvStr, final int imageResource) {
if (toast2 == null) {
toast2 = new Toast(BaseApplication.getAppContext());
}
View view = LayoutInflater.from(BaseApplication.getAppContext()).inflate(R.layout.toast_custom, null);
TextView tv = (TextView) view.findViewById(R.id.toast_custom_tv);
tv.setText(TextUtils.isEmpty(tvStr) ? "" : tvStr);
ImageView iv = (ImageView) view.findViewById(R.id.toast_custom_iv);
if (imageResource > 0) {
iv.setVisibility(View.VISIBLE);
iv.setImageResource(imageResource);
} else {
iv.setVisibility(View.GONE);
}
toast2.setView(view);
toast2.setGravity(Gravity.CENTER, 0, 0);
toast2.show();
return toast2;
}
}
- CollectionUtils
public class CollectionUtils {
/**
* 判断集合是否为null或者0个元素
*
* @param c
* @return
*/
public static boolean isNullOrEmpty(Collection c) {
if (null == c || c.isEmpty()) {
return true;
}
return false;
}
}
- ResourceUtil
public class ResourceUtil {
/**
* dip 转化成 px
*/
public static int dip2px(Context context, float dpValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dpValue * scale + 0.5f);
}
/**
* px 转化成dip
*/
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
/**
* px 转化成sp
*/
public static int px2sp(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
/**
* sp 转化成px
*/
public static int sp2px(Context context, float spValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(spValue / scale + 0.5f);
}
}
- LogUtil
public class L {
private static final boolean flag = true;
public static void i(String tag, String msg) {
if (flag)
Log.i(tag, msg);
}
public static void d(String tag, String msg) {
if (flag)
Log.d(tag, msg);
}
public static void e(String tag, String msg) {
if (flag)
Log.e(tag, msg);
}
public static void e(String tag, String msg, Throwable tr) {
if (flag)
Log.e(tag, msg, tr);
}
public static void v(String tag, String msg) {
if (flag)
Log.v(tag, msg);
}
public static void m(String tag, String msg) {
if (flag)
Log.e(tag, msg);
}
public static void w(String tag, String msg) {
if (flag)
Log.w(tag, msg);
}
}
- view 类
- MainPageActivity
public class MainPageActivity extends BaseActivity {
private static final String TAG = "MainPageActivity";
@BindView(R.id.main_toolbar)
Toolbar mToolbar;
@BindView(R.id.main_tab_layout)
TabLayout mTabLayout;
@BindView(R.id.main_view_pager)
ViewPager mViewPager;
@BindView(R.id.main_floating_action_btn)
FloatingActionButton mFloatingActionButton;
@BindView(R.id.main_drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.main_nav_view)
NavigationView mNavigationView;
private View mView;
private ImageView mImageView;
private String[] mModuleName = {"天气","穿搭","日程"};
private ArrayList<Fragment> mFragmentList = new ArrayList<Fragment>();
private ViewFragment mViewFragment;
private XMLFragment mXMLFragment;
private ShowFragment mShowFragment;
private HomeViewPagerAdapter homeViewPagerAdapter;
//private Unbinder mUnbinder;
@Override
public int getLayoutId(){
return R.layout.activity_main_page;
}
@Override
public void initPresenter() {
}
@Override
public void initView() {
//StatusBarSetting.setColorForDrawerLayout(this, mDrawerLayout, getResources().getColor(R.color.colorPrimary), StatusBarSetting.DEFAULT_STATUS_BAR_ALPHA);
setToolBar();
setNavigationView();
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//EventBus.getDefault().post(new FabScrollBean("滑动到顶端",mTabs.getSelectedTabPosition()));
}
});
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position==1||position==3){
mFloatingActionButton.setVisibility(View.VISIBLE);
}else{
mFloatingActionButton.setVisibility(View.GONE);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mUnbinder = ButterKnife.bind(this);
//setContentView(R.layout.activity_main_page);
initFragment(savedInstanceState);
setViewPager();
}
/**
* 填充ViewPager内容
*/
private void setViewPager() {
homeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager(), mFragmentList, Arrays.asList(mModuleName));
mViewPager.setAdapter(homeViewPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setTabTextColors(getResources().getColor(R.color.white), getResources().getColor(R.color.black));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager manager = getSupportFragmentManager();
if (mViewFragment.isAdded()) {
manager.putFragment(outState, "NewsFragment", mViewFragment);
}
if (mXMLFragment.isAdded()) {
manager.putFragment(outState, "FindFragment", mXMLFragment);
}
if (mShowFragment.isAdded()) {
manager.putFragment(outState, "VideoFragment", mShowFragment);
}
/*if (mNearByFragment.isAdded()) {
manager.putFragment(outState, "NearByFragment", mNearByFragment);
}
if (mMeiTuFragment.isAdded()) {
manager.putFragment(outState, "MeiTuFragment", mMeiTuFragment);
}
if (mMusicFragment.isAdded()) {
manager.putFragment(outState, "MusicFragment", mMusicFragment);
}
if (mRecommendFragment.isAdded()) {
manager.putFragment(outState, "RecommendFragment", mRecommendFragment);
}*/
}
/**
* 初始化fragment的记忆状态
*
* @param savedInstanceState
*/
private void initFragment(Bundle savedInstanceState) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (savedInstanceState != null) {
mViewFragment = (ViewFragment) getSupportFragmentManager().getFragment(savedInstanceState, "ViewFragment");
mXMLFragment = (XMLFragment) getSupportFragmentManager().getFragment(savedInstanceState, "XMLFragment");
mShowFragment = (ShowFragment) getSupportFragmentManager().getFragment(savedInstanceState, "ShowFragment");
/*mVideoFragment = (VideoFragment) getSupportFragmentManager().getFragment(savedInstanceState, "VideoFragment");
mNearByFragment = (NearByFragment) getSupportFragmentManager().getFragment(savedInstanceState, "NearByFragment");
mMeiTuFragment = (MeiTuFragment) getSupportFragmentManager().getFragment(savedInstanceState, "MeiTuFragment");
mMusicFragment = (MusicFragment) getSupportFragmentManager().getFragment(savedInstanceState, "MusicFragment");*/
} else {
mViewFragment = new ViewFragment();
mXMLFragment = new XMLFragment();
mShowFragment = new ShowFragment();
/* mVideoFragment = new VideoFragment();
mNearByFragment = new NearByFragment();
mMeiTuFragment = new MeiTuFragment();
mMusicFragment = new MusicFragment();*/
}
mFragmentList.add(mViewFragment);
mFragmentList.add(mXMLFragment);
mFragmentList.add(mShowFragment);
/*mFragmentList.add(mMeiTuFragment);
mFragmentList.add(mNearByFragment);
mFragmentList.add(mVideoFragment);
mFragmentList.add(mFindFragment);*/
}
/**
* 设置导航页信息
*/
private void setNavigationView() {
//NavigationView初始化
mNavigationView.setItemIconTintList(null);
View headerView = mNavigationView.getHeaderView(0);
mImageView = (ImageView) headerView.findViewById(R.id.iv_user_photo);
}
/**
* 设置状态栏
*/
private void setToolBar() {
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
//菜单按钮可用
actionBar.setHomeButtonEnabled(true);
//回退按钮可用
actionBar.setDisplayHomeAsUpEnabled(true);
//将drawlayout与toolbar绑定在一起
ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name, R.string.app_name);
abdt.syncState();//初始化状态
//设置drawlayout的监听事件 打开/关闭
mDrawerLayout.setDrawerListener(abdt);
//actionbar中的内容进行初始化
mToolbar.setTitle("设计器");//设置标题
mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
// mToolbar.setNavigationIcon(R.drawable.play_icn_src_prs);
}
/**
* 入口
*
* @param activity
*/
public static void startAction(Activity activity) {
Intent intent = new Intent(activity, MainPageActivity.class);
activity.startActivity(intent);
activity.overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_toolbar, menu);
return true;
}
}
- ShowFragment
public class ShowFragment extends Fragment {
private TimeLineMakerView timeLineMakerView1;
private TimeLineMakerView timeLineMakerView2;
private TimeLineMakerView timeLineMakerView3;
private TimeLineMakerView timeLineMakerView4;
private TimeLineMakerView timeLineMakerView5;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_show, container, false);
timeLineMakerView1 = (TimeLineMakerView)v.findViewById(R.id.time1);
timeLineMakerView2 = (TimeLineMakerView)v.findViewById(R.id.time2);
timeLineMakerView3 = (TimeLineMakerView)v.findViewById(R.id.time3);
timeLineMakerView4 = (TimeLineMakerView)v.findViewById(R.id.time4);
timeLineMakerView5 = (TimeLineMakerView)v.findViewById(R.id.time5);
Resources resources =getActivity().getResources();
timeLineMakerView1.setBeginLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView1.setEndLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView1.setMarkerDrawable(resources.getDrawable(R.drawable.timeline_bg_bule));
timeLineMakerView2.setBeginLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView2.setEndLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView2.setMarkerDrawable(resources.getDrawable(R.drawable.timeline_bg_bule));
timeLineMakerView3.setBeginLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView3.setEndLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView3.setMarkerDrawable(resources.getDrawable(R.drawable.timeline_bg_bule));
timeLineMakerView4.setBeginLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView4.setEndLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView4.setMarkerDrawable(resources.getDrawable(R.drawable.timeline_bg_bule));
timeLineMakerView5.setBeginLine(resources.getDrawable(R.color.blue_sky));
timeLineMakerView5.setEndLine(resources.getDrawable(R.color.colorAccent));
timeLineMakerView5.setMarkerDrawable(resources.getDrawable(R.drawable.timeline_bg_red));
return v;
}
}
- ViewFragment
public class ViewFragment extends Fragment {
private String TAG = "ViewFragment";
ArrayList<WeatherItem> mItem=new ArrayList<>();
//private Unbinder unbinder;
/* @BindView(R.id.btn_address)
private Button btn_address;
@BindView(R.id.tv_wea)
TextView tv_weather;
@BindView(R.id.et_time)
EditText et_time;
@BindView(R.id.tv_t)
TextView tv_temp;
@BindView(R.id.tv_win)
TextView tv_wind;*/
private Button btn_address;
private TextView tv_weather;
private TextView tv_temp;;
private TextView tv_wind;
private EditText et_time;
private String weather = "晴天";
private String temperature = "25";
private String wind_power = "3级";
private String temperature_time;
private String time;
private Calendar cal = Calendar.getInstance();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_view, container, false);
doGet(); //获取数据
initData(view); //初始化数据
btn_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv_weather.setText(weather);
tv_temp.setText(temperature);
tv_wind.setText(wind_power);
et_time.setText(time+temperature_time);
}
});
return view;
}
public void initData(View view){
btn_address = (Button)view.findViewById(R.id.btn_address);
tv_weather = (TextView)view.findViewById(R.id.tv_wea);
tv_temp = (TextView)view.findViewById(R.id.tv_t);
tv_wind = (TextView)view.findViewById(R.id.tv_win);
et_time = (EditText)view.findViewById(R.id.et_time);
tv_weather.setText(weather);
tv_temp.setText(temperature);
tv_wind.setText(wind_power);
int day = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
time = year +"年"+month+"月"+day+"日";
}
private boolean doGet(){
new Thread(new Runnable() {
@Override
public void run() {
try {
getWeather();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
return false;
}
/**
* 获取服务器数据
*/
public void getWeather(){
// String showapi_appid="48138";//要替换成自己的
// String showapi_sign="ede742069d024875a86520572b742c17";//要替换成自己的
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.POST, "http://route.showapi.com/9-2", new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.e("TAG", "onResponse: "+ s );
jsonParser(s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", "onErrorResponse: 错误" +error.toString());
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap();
map.put("showapi_appid","48138");
map.put("showapi_sign","ede742069d024875a86520572b742c17");
map.put("area", "广州");
return map;
}
};
queue.add(request);
}
//[4]解析数据
private void jsonParser(String jsonData) {
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject body = jsonObject.getJSONObject("showapi_res_body");
// time=body.getString("time");
// Log.i(TAG,"时间"+time);
JSONObject now = body.getJSONObject("now");
weather=now.optString("weather","defaultValue");
temperature=now.optString("temperature","defaultValue");
wind_power=now.optString("wind_power","defaultValue");
temperature_time = now.optString("temperature_time","defaultValue");
Log.i(TAG,"天气"+weather);
Log.i(TAG,"温度"+temperature);
Log.i(TAG,"风力"+wind_power);
Log.i(TAG,"时刻"+temperature_time);
} catch (JSONException e) {
e.printStackTrace();
}
}
//[6]保存数据
private void saveSelectData(String text){
SharedPreferencesUtils preferences=getSharedPreferences("SceneTwo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("weather", weather);
editor.putString("temperature", temperature);
editor.apply();
L.i(TAG,"temperature"+temperature);
}
}
- XMLFragment
public class XMLFragment extends Fragment {
private ImageView iv_bg;
private TextView tv_change;
private final static int MIN_TEMP = 1; //低温
private final static int MID_TEMP = 2; //常温
private final static int MAX_TEMP = 3; //高温
private int count = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_xml, container, false);
iv_bg = (ImageView)view.findViewById(R.id.iv_bg);
tv_change = (TextView)view.findViewById(R.id.tv_change);
tv_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (count == 4){
count = 0;
}
else{
count = count +1;
ChangeColoth(count);
}
}
});
return view;
}
public void ChangeColoth(int temp){
switch (temp){
case MIN_TEMP:
iv_bg.setBackgroundResource(R.drawable.im_bg_1);
break;
case MID_TEMP:
iv_bg.setBackgroundResource(R.drawable.im_bg_2);
break;
case MAX_TEMP:
iv_bg.setBackgroundResource(R.drawable.im_bg_4);
break;
}
}
}
[5] 测试
android 5.0 系统以上