android Fragment和FragmentActivity

MainActivity.java




import android.app.AlertDialog; import android.app.Notification; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.baidu.android.pushservice.CustomPushNotificationBuilder; import com.baidu.android.pushservice.PushConstants; import com.baidu.android.pushservice.PushManager; import com.example.newpingziyi.push.Utils; import com.example.newpingziyi.stir.WebViews; import com.example.newpingziyi.system.SettingActivity; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; public class MainActivity extends FragmentActivity { private ViewPager mPager; private TextView tv_find; private TextView tv_my_file; private TextView mainhead; private SlidingMenu slidingMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Utils.logStringCache = Utils.getLogText(getApplicationContext()); Resources resource = this.getResources(); String pkgName = this.getPackageName(); // PushManager.startWork(getApplicationContext(), // PushConstants.LOGIN_TYPE_API_KEY, // Utils.getMetaValue(MainActivity.this, "api_key")); findView(); init(); if (!Utils.hasBind(getApplicationContext())) { PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, Utils.getMetaValue(MainActivity.this, "api_key")); // Push: 如果想基于地理位置推送,可以打开支持地理位置的推送的开关 PushManager.enableLbs(getApplicationContext()); } CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder( getApplicationContext(), resource.getIdentifier( "notification_custom_builder", "layout", pkgName), resource.getIdentifier("notification_icon", "id", pkgName), resource.getIdentifier("notification_title", "id", pkgName), resource.getIdentifier("notification_text", "id", pkgName)); cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL); cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); cBuilder.setStatusbarIcon(this.getApplicationInfo().icon); cBuilder.setLayoutDrawable(resource.getIdentifier("logo_notification", "drawable", pkgName)); PushManager.setNotificationBuilder(this, 1, cBuilder); } private void findView() { mPager = (ViewPager) findViewById(R.id.vPager); tv_find = (TextView) findViewById(R.id.tv_find); tv_my_file = (TextView) findViewById(R.id.tv_my_file); mainhead = (TextView) findViewById(R.id.main_head); tv_find.setOnClickListener(new MyOnClickListener(0)); tv_my_file.setOnClickListener(new MyOnClickListener(1)); mainhead.setOnClickListener(new View.OnClickListener() { int version = Integer.valueOf(android.os.Build.VERSION.SDK); @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebViews.class); startActivity(intent); if (version >= 5) { MainActivity.this.overridePendingTransition( R.anim.push_left_in, R.anim.push_left_out); } } }); } private void init() { mPager.setAdapter(new ContentPagerAdapter(getSupportFragmentManager())); mPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { setCurrentPage(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // ignore } public void onPageScrollStateChanged(int state) { // ignore } }); slidingMenu = new SlidingMenu(MainActivity.this); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); slidingMenu.setShadowDrawable(R.drawable.shadow_right); slidingMenu.setShadowWidth(getWindowManager().getDefaultDisplay() .getWidth() / 40); // slidingMenu.setShadowWidth(20); // slidingMenu.setBehindOffset(40); slidingMenu.setBehindOffset(getWindowManager().getDefaultDisplay() .getWidth() / 5); slidingMenu.setMode(SlidingMenu.LEFT); slidingMenu.setFadeEnabled(true); slidingMenu.setFadeDegree(0.4f); slidingMenu.setBehindScrollScale(0); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); slidingMenu.setSlidingEnabled(true); slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT); slidingMenu.setMenu(R.layout.menu_frame); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction().replace(R.id.menu_frame, new SettingActivity()) .commit(); } @Override public void onBackPressed() { if (slidingMenu != null && slidingMenu.isMenuShowing()) { slidingMenu.showContent(); } else { super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { slidingMenu.toggle(); return true; } else if (keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog isExit = new AlertDialog.Builder(this).create(); isExit.setTitle("系统提示"); isExit.setMessage("确定要退出吗"); isExit.setButton("确定", listener); isExit.setButton2("取消", listener); isExit.show(); } return super.onKeyDown(keyCode, event); } DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_POSITIVE: Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); System.exit(0); break; case AlertDialog.BUTTON_NEGATIVE: break; default: break; } } }; private void setCurrentPage(int current) { if (current == 0) { tv_find.setTextColor(getResources().getColor(R.color.green)); tv_my_file.setTextColor(getResources().getColor(R.color.grey)); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); } else { tv_my_file.setTextColor(getResources().getColor(R.color.green)); tv_find.setTextColor(getResources().getColor(R.color.grey)); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); } } private class MyOnClickListener implements OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } public void onClick(View v) { mPager.setCurrentItem(index); } } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { Utils.setLogText(getApplicationContext(), Utils.logStringCache); super.onDestroy(); } }

  MenuItem.java

主页面的一些菜单

public class MenuItem {
	public int menuIconRes;
	public String menuTitle;
	public String menuMsg;

	public MenuItem(int menuIconRes, String menuTitle, String menuMsg) {
		this.menuIconRes = menuIconRes;
		this.menuTitle = menuTitle;
		this.menuMsg = menuMsg;
	}

  MenuItemAdapter.java

菜单的适配器

public class MenuItemAdapter extends BaseAdapter {

	private List<MenuItem> menus;
	private LayoutInflater inflater;
	private int margin;

	public MenuItemAdapter(Context context, List<MenuItem> menus, int margin) {
		inflater = LayoutInflater.from(context);
		this.menus = menus;
		this.margin = margin;
	}

	@Override
	public int getCount() {
		return menus.size();
	}

	@Override
	public Object getItem(int position) {
		return menus.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		int height = parent.getHeight() / 3 - margin;
		AbsListView.LayoutParams param = new AbsListView.LayoutParams(
				LayoutParams.MATCH_PARENT, height);
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.menu_item, parent, false);
			holder = new ViewHolder();
			holder.iv_menuIcon = (ImageView) convertView
					.findViewById(R.id.iv_menu_icon);
			holder.tv_menuTitle = (TextView) convertView
					.findViewById(R.id.tv_menu_title);
			holder.tv_menuMsg = (TextView) convertView
					.findViewById(R.id.tv_menu_msg);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		MenuItem item = menus.get(position);
		holder.iv_menuIcon.setImageResource(item.menuIconRes);
		holder.tv_menuTitle.setText(item.menuTitle);
		if (item.menuMsg.length() == 0) {
			holder.tv_menuMsg.setVisibility(View.GONE);
		} else {
			holder.tv_menuMsg.setVisibility(View.VISIBLE);
			holder.tv_menuMsg.setText(item.menuMsg);
		}
		convertView.setLayoutParams(param);
		return convertView;
	}

	private class ViewHolder {
		ImageView iv_menuIcon;
		TextView tv_menuTitle;
		TextView tv_menuMsg;
	}

}

  FindFragment.java

主页面Fragment

public class FindFragment extends Fragment implements OnItemClickListener {
	private static final String SAVED_IMAGE_DIR_PATH = "photo_path";
	private static final int SELECT_PIC_BY_TACK_PHOTO = 1;
	private static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	private static final String TAG = "FindFragment";
	private SharedPreferences preferences;
	private GridView gv_menu;
	private String picPath;
	private Uri photoUri;
	private String user;
	private FindFragment mFragment;

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_find, container, false);
		findView(view);
		init();
		return view;
	}

	private void findView(View v) {
		gv_menu = (GridView) v.findViewById(R.id.gv_menu);
		gv_menu.setOnItemClickListener(this);
		preferences = getActivity().getSharedPreferences("UserInfo",
				getActivity().MODE_PRIVATE);
		user = preferences.getString("NAME", user);
	}

	private void init() {
		List<MenuItem> menus = new ArrayList<MenuItem>();
		menus.add(new MenuItem(R.drawable.msg, "消息", "最新情报"));
		menus.add(new MenuItem(R.drawable.servicer, "服务", "服务与产品"));
		menus.add(new MenuItem(R.drawable.take_photo, "拍照上传", ""));
		menus.add(new MenuItem(R.drawable.pick_photo, "相册上传", ""));
		menus.add(new MenuItem(R.drawable.share, "分享", "推荐给朋友"));
		menus.add(new MenuItem(R.drawable.teapot, "泡茶", "即将开启你的私人助手"));

		int margin = (int) (getResources().getDisplayMetrics().density * 14 * 13 / 9);
		MenuItemAdapter adapter = new MenuItemAdapter(getActivity(), menus,
				margin);
		gv_menu.setAdapter(adapter);
	}

	private int[] menu = { R.drawable.msg, R.drawable.servicer,
			R.drawable.take_photo, R.drawable.pick_photo, R.drawable.share,
			R.drawable.teapot };

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		switch (menu[position]) {
		case R.drawable.msg:
			Intent msg = new Intent(getActivity(), StirActivity.class);
			startActivity(msg);
			translate();
			break;

		case R.drawable.servicer:
			Intent mWeb = new Intent(getActivity(), WebService.class);
			startActivity(mWeb);
			translate();
			break;
		case R.drawable.teapot:
			// Intent set = new Intent(getActivity(), SettingActivity.class);
			// startActivity(set);
			Toast.makeText(getActivity(), R.string.pending, 1).show();
			break;
		case R.drawable.take_photo:
			if (user != null) {
				takePhoto();
				translate();
			} else {
				login();
			}
			break;
		case R.drawable.pick_photo:
			if (user != null) {
				pickPhoto();
				translate();
			} else {
				login();
			}
			break;
		case R.drawable.share:
			Intent share = new Intent(Intent.ACTION_SEND);
			share.setType("text/plain");
			share.putExtra(Intent.EXTRA_SUBJECT, R.string.main_share);
			share.putExtra(Intent.EXTRA_TEXT, R.string.main_share_content);
			startActivity(share.createChooser(share, getActivity().getTitle()));
			break;
		}
	}

	// takePhoto
	private void takePhoto() {
		String SDState = Environment.getExternalStorageState();
		if (SDState.equals(Environment.MEDIA_MOUNTED)) {

			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			ContentValues values = new ContentValues();
			photoUri = getActivity().getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
			startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
			if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
				Toast.makeText(getActivity(), R.string.take_photo_rem, 1)
						.show();
			}
		} else {
			Toast.makeText(getActivity(), R.string.takePhoto_msg, 1).show();
		}
	}

	// pickPhoto
	private void pickPhoto() {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case SELECT_PIC_BY_PICK_PHOTO:
				if (data != null) {
					photoUri = data.getData();
					String[] pojo = { MediaStore.Images.Media.DATA };
					Cursor cursor = getActivity().getContentResolver().query(
							photoUri, pojo, null, null, null);
					if (cursor != null) {
						int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
						cursor.moveToLast();
						picPath = cursor.getString(columnIndex);
						try {
							if (Integer.parseInt(Build.VERSION.SDK) < 14) {
								cursor.close();
							}
						} catch (Exception e) {
							Log.e(TAG, "error:" + e);
						}
					}
				} else {
					Toast.makeText(getActivity(), R.string.photo_err, 1).show();
					return;
				}
				break;
			case SELECT_PIC_BY_TACK_PHOTO:
				if (photoUri != null) {
					String[] pojo = { MediaStore.Images.Media.DATA };
					Cursor cursor = getActivity().getContentResolver().query(
							photoUri, pojo, null, null, null);
					if (cursor != null) {
						int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
						cursor.moveToLast();
						picPath = cursor.getString(columnIndex);
						try {
							if (Integer.parseInt(Build.VERSION.SDK) < 14) {
								cursor.close();
							}
						} catch (Exception e) {
							Log.e(TAG, "error:" + e);
						}
					}
				} else {
					Toast.makeText(getActivity(), R.string.tackphoto_err, 1)
							.show();
					return;
				}

				break;
			default:
				break;
			}
			if (picPath != null) {
				Intent startEx = new Intent(getActivity(), PhotoPre.class);
				startEx.putExtra(SAVED_IMAGE_DIR_PATH, picPath);
				startActivity(startEx);
			} else {
				Toast.makeText(getActivity(), R.string.photo_err, 1).show();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void translate() {
		int version = Integer.valueOf(android.os.Build.VERSION.SDK);
		if (version >= 5) {
			getActivity().overridePendingTransition(R.anim.push_left_in,
					R.anim.push_left_out);
		}
	}

	private void login() {
		Toast toast = Toast.makeText(getActivity(), R.string.on_login, 1);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				Intent login = new Intent(getActivity(), Login.class);
				startActivity(login);
				translate();
			}
		}, 1500);
	}

  CheckSdcard.java

次页面:

public class CheckSdcard extends Fragment implements OnItemClickListener,
		OnItemLongClickListener {
	private ListView sdcardImages;
	private ImageButton img_btn;
	private ImageAdapter imageAdapter;
	private Display display;
	private ArrayList<LoadedImage> mPhotos = new ArrayList<LoadedImage>();
	private String ftpPath = "/";
	private String user;
	private String localPath = Environment.getExternalStorageDirectory()
			+ "/pingziyi";
	private TextView mTextView;
	

	private PopupWindow popupWindow = null;
	private int screenWidth = 0;
	private int screenHeight = 0;
	private int popupWindowWidth = 0;
	private int popupWindowHeight = 0;
	private TextView layout_check;
	private TextView layout_delete;
	private View convertview;
	private boolean running;
	private ProgressWheel pw_two;;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.share_photo, container, false);
		connect();
		setupViews(view);
		if (connect() == true) {
			if (checkFile() == true) {
				loadImages();
			}
		}
		return view;
	}

	public boolean checkFile() {
		File file = new File(localPath + "/");
		File[] f = file.listFiles();
		if (f != null && f.length > 0) {
			return true;
		} else {
			return false;
		}
	}

	public void onDestroy() {
		super.onDestroy();
	}

	private boolean connect() {
		new Thread(new Runnable() {
			ContinueFTP ftp = new PhotoPre.ContinueFTP();

			public void run() {
				Looper.prepare();
				ftp = new PhotoPre.ContinueFTP();
				try {
					ftp.connect("125.88.22.1x7", 21, "xxxx", "&xxxx,");
					List<String> path = new ArrayList<String>();
					path = ftp.getListFiles(ftpPath);
					boolean sdCardExist = Environment.getExternalStorageState()
							.equals(android.os.Environment.MEDIA_MOUNTED);
					if (!sdCardExist) {
						Toast.makeText(getActivity(), R.string.insert_sdcard,
								Toast.LENGTH_SHORT).show();
					} else {
						File dir = new File(localPath + "/");
						if (!dir.exists()) {
							dir.mkdir();
						}
					}
					for (String str : path) {
						String filename = str;
						String result = filename.substring(
								filename.indexOf("_") + 1,
								filename.indexOf("."));
						SharedPreferences sp = getActivity()
								.getSharedPreferences("UserInfo",
										getActivity().MODE_PRIVATE);
						user = sp.getString("NAME", user);
						try {
							Thread.sleep(200);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						if (result.equals(user)) {
							String remote = ftpPath + str;
							String remotelocal = localPath + "/" + str;

							ftp.download(remote, remotelocal);
						}
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		return true;
	}

	private void setupViews(View view) {
		sdcardImages = (ListView) view.findViewById(R.id.list_share);
		img_btn = (ImageButton) view.findViewById(R.id.reflesh);
		mTextView = (TextView) view.findViewById(R.id.no_pic);
		pw_two = (ProgressWheel) view.findViewById(R.id.progressbartwo);
		img_btn.setOnClickListener(new RefreshButton());
		sdcardImages.setOnItemClickListener(this);
		sdcardImages.setOnCreateContextMenuListener(new DeleteItem());
		sdcardImages.setOnItemLongClickListener(this);
		sdcardImages.setClipToPadding(false);
		imageAdapter = new ImageAdapter(getActivity());
		sdcardImages.setAdapter(imageAdapter);
		imageAdapter.notifyDataSetChanged();
		sdcardImages.setEmptyView(mTextView);

	}

	private class DeleteItem implements OnCreateContextMenuListener {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			menu.add(0, 0, 0, "查看");
			menu.add(0, 1, 0, "删除");
		}

	};

	@SuppressLint("NewApi")
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int itemId = item.getItemId();
		int pos = (int) imageAdapter.getItemId(menuInfo.position);
		String path = imageAdapter.getPhoto().get(pos).getPath();
		final String filename = imageAdapter.getPhoto().get(pos).getName();
		System.out.println("filename---------ftp-----" + filename);
		switch (itemId) {
		case 0:
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			System.out.println("path-------" + path);
			Bitmap bm = BitmapFactory.decodeFile(path);
			if (bm != null) {
				View img = inflater.inflate(R.layout.dialog_view, null);
				ImageView view = (ImageView) img.findViewById(R.id.imgView);
				final AlertDialog dialog = new AlertDialog.Builder(
						getActivity(), R.style.Translucent_NoTitle).create();
				view.setImageBitmap(bm);
				dialog.setView(img);
				dialog.show();

				view.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.cancel();
					}
				});
			} else {
				Toast.makeText(getActivity(), "没有图片可以浏览!", 1).show();
			}
			break;

		case 1:
			mPhotos.remove(pos);
			imageAdapter.notifyDataSetChanged();
			sdcardImages.invalidate();
			File f = new File(path);
			f.delete();
			new Thread(new Runnable() {
				@Override
				public void run() {
					Looper.prepare();
					try {
						ftp.connect("125.88.22.1x7", 21, "xxxx",
								"&xxxxx,");
						ftp.deleteLoadFile("/" + filename);
						Toast.makeText(getActivity(), "图片删除成功!", 1).show();
					} catch (IOException e) {
						Toast.makeText(getActivity(), "图片删除失败!", 1).show();
						e.printStackTrace();
					}
				}
			}).start();
			break;
		}

		return true;
	}

	public void onContextMenuClosed(Menu menu) {

		super.getActivity().onContextMenuClosed(menu);
	}

	private void loadImages() {
		final Object data = getActivity().getLastNonConfigurationInstance();
		if (data == null) {
			new LoadImagesFromSDCard().execute();
			progress();
		} else {
			final LoadedImage[] photos = (LoadedImage[]) data;
			if (photos.length == 0) {
				new LoadImagesFromSDCard().execute();
				progress();
			}
			for (LoadedImage photo : photos) {
				addImage(photo);
			}
		}
	}

	private void addImage(LoadedImage... value) {
		for (LoadedImage image : value) {
			imageAdapter.addPhoto(image);
			imageAdapter.notifyDataSetChanged();
		}
	}

	class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
		@Override
		protected Object doInBackground(Object... params) {

			Bitmap newBitmap = null;
			File file = new File(localPath);
			String[] filepath = file.list();
			for (String str : filepath) {
				String filename = str;
				String imagePath = localPath + "/" + filename;
				File files = new File(imagePath);

				FileInputStream is = null;
				BufferedInputStream bis = null;

				BitmapFactory.Options opts = new BitmapFactory.Options();

				if (files.length() < 51200) { // 20-50k
					opts.inSampleSize = 2;
				} else if (files.length() < 307200) { // 50-300k
					opts.inSampleSize = 4;
				} else if (files.length() < 819200) { // 300-800k
					opts.inSampleSize = 6;
				} else if (files.length() < 1048576) { // 800-1024k
					opts.inSampleSize = 8;
				} else {
					opts.inSampleSize = 12;
				}

				Bitmap bitmap = BitmapFactory.decodeFile(files.getPath(), opts);

				long size = files.length();
				DecimalFormat df = new DecimalFormat("#.00");
				String fileSizeString = "";
				if (size < 1024) {
					fileSizeString = df.format((double) size) + "B";
				} else if (size < 1048576) {
					fileSizeString = df.format((double) size / 1024) + "K";
				} else if (size < 1073741824) {
					fileSizeString = df.format((double) size / 1048576) + "M";
				} else {
					fileSizeString = df.format((double) size / 1073741824)
							+ "G";
				}

				long time = files.lastModified();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(time);

				String date = cal.getTime().toLocaleString();
				if (bitmap != null) {

					newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
					bitmap.recycle();
					bitmap = null;
					if (newBitmap != null) {
						publishProgress(new LoadedImage(newBitmap, date,
								fileSizeString, filename, imagePath));
					}
				}
			}
			return null;
		}

		@Override
		public void onProgressUpdate(LoadedImage... value) {
			addImage(value);
		}

		@Override
		protected void onPostExecute(Object result) {
			pw_two.setVisibility(View.GONE);
			imageAdapter.notifyDataSetChanged();
		}
	}

	class ImageAdapter extends BaseAdapter {
		private Context mContext;

		public ImageAdapter(Context context) {
			mContext = context;
		}

		public void addPhoto(LoadedImage photo) {
			mPhotos.add(photo);
			notifyDataSetChanged();
		}

		public int getCount() {
			return mPhotos == null ? 0 : mPhotos.size();
		}

		public Object getItem(int position) {
			return mPhotos == null ? null : mPhotos.get(position);
		}

		public ArrayList<LoadedImage> getPhoto() {
			return mPhotos;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				final ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.share_content, null);
				viewHolder.tv_name = (TextView) convertView
						.findViewById(R.id.photo_name);
				viewHolder.tv_time = (TextView) convertView
						.findViewById(R.id.photo_time);
				viewHolder.tv_size = (TextView) convertView
						.findViewById(R.id.photo_size);
				viewHolder.img_icon = (ImageView) convertView
						.findViewById(R.id.photo);
				viewHolder.img_btn = (ImageButton) convertView
						.findViewById(R.id.img_operate);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			viewHolder.tv_name.setText(mPhotos.get(position).getName());
			viewHolder.tv_time.setText(mPhotos.get(position).getFileDateTime());
			viewHolder.tv_size.setText(mPhotos.get(position).getBitmapSize());
			viewHolder.img_icon.setImageBitmap(mPhotos.get(position)
					.getBitmap());
			viewHolder.img_btn.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (popupWindow != null) {
						popupWindow.dismiss();
					} else {
						initPopupWindow(v, position);
					}
					return true;
				}
			});
			return convertView;

		}

		class ViewHolder {
			TextView tv_name;
			TextView tv_time;
			TextView tv_size;
			ImageView img_icon;
			ImageButton img_btn;
		}
	}

	private static class LoadedImage {
		Bitmap mBitmap;
		String mDate;
		String mSize;
		String mFilename;
		String mPath;

		LoadedImage(Bitmap bitmap, String date, String size, String filename,
				String path) {
			mBitmap = bitmap;
			mDate = date;
			mSize = size;
			mFilename = filename;
			mPath = path;
		}

		public Bitmap getBitmap() {
			return mBitmap;
		}

		public String getName() {
			return mFilename;
		}

		public String getBitmapSize() {
			return mSize;
		}

		public String getFileDateTime() {
			return mDate;
		}

		public String getPath() {
			return mPath;

		}

	}

	@SuppressLint("NewApi")
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		String path = imageAdapter.getPhoto().get(position).getPath();
		System.out.println("path-------" + path);
		Bitmap bm = BitmapFactory.decodeFile(path);
		if (bm != null) {
			View img = inflater.inflate(R.layout.dialog_view, null);
			ImageView view = (ImageView) img.findViewById(R.id.imgView);
			final AlertDialog dialog = new AlertDialog.Builder(getActivity(),
					R.style.Translucent_NoTitle).create();
			view.setImageBitmap(bm);
			dialog.setView(img);
			dialog.show();

			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.cancel();
				}
			});
		} else {
			Toast.makeText(getActivity(), "没有图片可以浏览!", 1).show();
		}
	}

	// 点击刷新
	class RefreshButton implements OnClickListener {

		public void onClick(View v) {
			connect();
			mPhotos.clear();
			loadImages();
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		return false;
	}

	private void initPopupWindow(View convertView, int position) {
		final int pos = (int) imageAdapter.getItemId(position);
		final String path = imageAdapter.getPhoto().get(pos).getPath();
		final String filename = imageAdapter.getPhoto().get(pos).getName();

		// RelativeLayout pv = (RelativeLayout) LayoutInflater.from(
		// getActivity()).inflate(R.layout.popupwindow, null);

		// popupWindow = new PopupWindow(getActivity());
		// popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// popupWindow.setContentView(pv);

		// popupWindow.setWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth()
		// / 3);
		// popupWindow.setHeight(60);

		// popupWindow.setOutsideTouchable(true);
		// popupWindow.setFocusable(true);

		screenWidth = getActivity().getWindowManager().getDefaultDisplay()
				.getWidth();
		screenHeight = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight();
		View popupWindow_view = getActivity().getLayoutInflater().inflate(
				R.layout.popupwindow, null, false);
		popupWindow = new PopupWindow(popupWindow_view, screenWidth - 40,
				screenHeight / 3 - 20, true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setContentView(popupWindow_view);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// popupWindow.showAsDropDown(convertView);
		popupWindow
				.showAtLocation(convertView, Gravity.LEFT | Gravity.TOP,
						getActivity().getWindowManager().getDefaultDisplay()
								.getWidth() / 4,
						getStateBar() + convertView.getHeight()
								* (position + 1));
		layout_check = (TextView) popupWindow_view.findViewById(R.id.check);
		layout_delete = (TextView) popupWindow_view.findViewById(R.id.delete);
		layout_check.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater.from(getActivity());
				System.out.println("path-------" + path);
				Bitmap bm = BitmapFactory.decodeFile(path);
				if (bm != null) {
					View img = inflater.inflate(R.layout.dialog_view, null);
					ImageView view = (ImageView) img.findViewById(R.id.imgView);
					final AlertDialog dialog = new AlertDialog.Builder(
							getActivity(), R.style.Translucent_NoTitle)
							.create();
					view.setImageBitmap(bm);
					dialog.setView(img);
					dialog.show();
					view.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					});
				} else {
					Toast.makeText(getActivity(), "没有图片可以浏览!", 1).show();
				}
			}
		});
		layout_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPhotos.remove(pos);
				imageAdapter.notifyDataSetChanged();
				sdcardImages.invalidate();
				File f = new File(path);
				f.delete();
				new Thread(new Runnable() {
					@Override
					public void run() {
						Looper.prepare();
						try {
							ftp.connect("125.88.22.147", 21, "tea_system",
									"&UJM8ik,");
							ftp.deleteLoadFile("/" + filename);
							Toast.makeText(getActivity(), "图片删除成功!", 1).show();
						} catch (IOException e) {
							Toast.makeText(getActivity(), "图片删除失败!", 1).show();
							e.printStackTrace();
						}
					}
				}).start();
			}
		});

		popupWindowHeight = popupWindow.getHeight();
		popupWindowWidth = popupWindow.getWidth();
	}

	
	
}

  ContentPagerAdapter.java

Fragment适配器

public class ContentPagerAdapter extends FragmentPagerAdapter {

	private Fragment[] fragments;

	public ContentPagerAdapter(FragmentManager fm) {
		super(fm);
		fragments = new Fragment[2];
		fragments[0] = new FindFragment();
		fragments[1] = new CheckSdcard();
	}

	@Override
	public Fragment getItem(int position) {
		return fragments[position];
	}

	@Override
	public int getCount() {
		return fragments.length;
	}
}

  

posted @ 2013-12-23 09:57  上风华  阅读(2509)  评论(0编辑  收藏  举报