栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android仿微信键盘切换效果

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android仿微信键盘切换效果

Android 仿微信的键盘切换(录音,表情,文字,其他),IM通讯,类似朋友圈只要涉及到文字等相关的app都会要涉及到键盘的处理,今天就给大家分享一下Android 仿微信的键盘切换。

效果图如下:

Android 仿微信的键盘切换,实现了录音、表情、其他和软键盘显示之间的切换,其中解决了很多博客介绍的键盘切换时,软键盘显示切换到表情(其他)时,出现屏幕晃动的情况,以及点击和滑动键盘显示区域外时,软键盘隐藏的功能等,废话不多说直接上代码,以供大家参考:

xml:




 

 

 

 


 

 

 

 
 
 
 
 
 
 

 
 

 

 

 


 


 

 
 
 
 
 
 
 

 


 

 

 

 
 

  

  
  

  

  

  


  

  


 


 
 

  

  

 

 
 


  

  

  

  

  


  


  

  


  

  

  


  

  
  
  
  

 


 


 


 


 
 

 

 

 

 


 
 
 


xml布局中用到了自定义KeyboardListenRelativeLayout(判断软键盘显示和隐藏的自定义控件)

package com.motoband.ui.view;


import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;


public class KeyboardListenRelativeLayout extends RelativeLayout {

 private static final String TAG = KeyboardListenRelativeLayout.class.getSimpleName();

 public static final byte KEYBOARD_STATE_SHOW = -3;
 public static final byte KEYBOARD_STATE_HIDE = -2;
 public static final byte KEYBOARD_STATE_INIT = -1;

 private boolean mHasInit = false;
 private boolean mHasKeyboard = false;
 private int mHeight;

 private IonKeyboardStateChangedListener onKeyboardStateChangedListener;

 public KeyboardListenRelativeLayout(Context context) {
 super(context);
 }
 public KeyboardListenRelativeLayout(Context context, AttributeSet attrs) {
 super(context, attrs);
 }

 public KeyboardListenRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
 super(context, attrs, defStyle);
 }

 public void setonKeyboardStateChangedListener(IonKeyboardStateChangedListener onKeyboardStateChangedListener) {
 this.onKeyboardStateChangedListener = onKeyboardStateChangedListener;
 }

 @Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
 super.onLayout(changed, l, t, r, b);
 if(!mHasInit) {
 mHasInit = true;
 mHeight = b;
 if(onKeyboardStateChangedListener != null) {
 onKeyboardStateChangedListener.onKeyboardStateChanged(KEYBOARD_STATE_INIT);
 }
 } else {
 mHeight = mHeight < b ? b : mHeight;
 }

 if(mHasInit && mHeight > b) {
 mHasKeyboard = true;
 if(onKeyboardStateChangedListener != null) {
 onKeyboardStateChangedListener.onKeyboardStateChanged(KEYBOARD_STATE_SHOW);
 }
 }
 if(mHasInit && mHasKeyboard && mHeight == b) {
 mHasKeyboard = false;
 if(onKeyboardStateChangedListener != null) {
 onKeyboardStateChangedListener.onKeyboardStateChanged(KEYBOARD_STATE_HIDE);
 }
 }
 }

 public interface IonKeyboardStateChangedListener {
 public void onKeyboardStateChanged(int state);
 }
}

下面直接步入正题来介绍代码中实现的键盘切换:

package com.motoband.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.alertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.baseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.motoband.R;
import com.motoband.core.manager.LoginManager;
import com.motoband.core.manager.MBUserManager;
import com.motoband.core.model.MBUserModel;
import com.motoband.core.utils.MBUtil;
import com.motoband.mbcamera.camera.CameraConstants;
import com.motoband.ui.Voice.AudioRecorder;
import com.motoband.ui.Voice.RecordButton;
import com.motoband.ui.manager.PixelOrdpManager;
import com.motoband.ui.manager.SoftKeyboardManager;
import com.motoband.ui.manager.StatusBarManager;
import com.motoband.ui.view.KeyboardListenRelativeLayout;
import com.motoband.ui.view.MyEditText;
import com.motoband.ui.view.MyGridView;
import com.motoband.widget.RoundImageView;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ChatActivity extends AppCompatActivity implements LocationSource,AMapLocationListener,GeocodeSearch.onGeocodeSearchListener {


 private Intent intent;
 private MBUserModel mbUserModel;
 private MBUserModel meMBUserModel;
 //聊天对象
 private TextView txt_im_object_name;

 private ListView listView;
// private ChatAdapter chatAdapter;


 //信息内容
 private MyEditText txt_im_message;

 //键盘
 //最外层判断软键盘是否弹出的
 private KeyboardListenRelativeLayout keyboardListenRelativeLayout;

 //语音
 private ImageView img_voice;
 //录音
 private TextView txt_record;
 private RelativeLayout layout_voice;
 private ImageView img_im_microphone_state;
 private ImageView img_im_microphone_sound_size;
 private TextView txt_im_microphone_show_text;

 //表情
 private ImageView img_expression;

 //其他 照片 拍摄 小视频 位置
 private ImageView img_other;
 //其他的显示
 private RelativeLayout layout_other;
 //照片
 private ImageView im_chat_poto;
 // 拍摄
 private ImageView im_chat_camera;
 //照片路径
 private String picStringUrl;
 // 小视频
 private ImageView im_chat_video;
 // 位置
 private ImageView im_chat_location;
 //位置的照片 //地图
 private ScrollView scrollView_location_bitmap;
 private MapView mapView;//骑行地图 TextureMapView
 private AMap aMap;//骑行地图
 private ImageView img_location_map;
 //定位
 private AMapLocationClient mLocationClient;
 private LocationSource.onLocationChangedListener mListener;
 private LatLonPoint latLonPoint;
 private GeocodeSearch geocodeSearch;
 //获取的当前位置
 private LocationManager locationManager;
 private String locationProvider;
 Location location;
 //经纬度
 private double latitude;
 private double longitude;
 //判断是点击的还是移动地图的 false 移动地图 true 点击
 private boolean isFirst=false;
 private boolean isShowMoveLocationCenter=true;
 // 获取当前地图中心点的坐标
 LatLng mTarget;
 //地图中心点当前的具体位置
// private LatLng currentlatLng;
 private String currentSpecificPosition;
// private ImageView img_bitmap;




 //语音
 private boolean isShowVoice = false;
 //表情
 private boolean isShowexpressionViewpager = false;
 //其他
 private boolean isShowOther = false;
 private RelativeLayout layout_expression;
 private ViewPager viewPager;
 private ViewPagerAdapter viewPagerAdapter;
 private List viewsList;
 
 private ImageView[] imageViews;
 //包裹小圆点的LinearLayout
 private LinearLayout viewPoints;
 private ImageView imageView;
 //第一组表情
 private MyGridView myGridViewExpresionOne;
 ArrayList unicodeOne = new ArrayList();
 //第二组表情
 private MyGridView myGridViewExpresionTwo;
 ArrayList unicodeTwo = new ArrayList();
 //第三组表情
 private MyGridView myGridViewExpresionThere;
 ArrayList unicodeThere = new ArrayList();
 private GridAdapter gridAdapter;

 //当前选择的是录音 表情 其他 并且显示 1 2 3
 private int currentSelect = 0;

// RecordButton button;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_chat);
 //在进入有VideoView界面的Activity时会出现闪黑屏的情况(如论视频是否播放):
 getWindow().setFormat(PixelFormat.TRANSLUCENT);
 //状态栏颜色的设置
 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.linearlayout_main);
 StatusBarManager.SetStatusBar(getWindow(), this, getResources(), "#1F2B29", linearLayout);

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

 initMap(savedInstanceState);
 initView();
 initData();
 initListener();

// button = (RecordButton) findViewById(R.id.btn_record);
// button.setAudioRecord(new AudioRecorder());
// button.setRecordListener(new RecordButton.RecordListener() {
// @Override
// public void recordEnd(String filePath) {
//
//
// }
// });
 }


 private void initView() {
// img_bitmap= (ImageView) findViewById(R.id.img_bitmap);
 listView = (ListView) findViewById(R.id.listView);
 txt_im_object_name = (TextView) findViewById(R.id.txt_im_object_name);
 //说点什么
 txt_im_message = (MyEditText) findViewById(R.id.txt_im_message);
 txt_im_message.setSelection(txt_im_message.getText().length());
 //录音
 txt_record = (TextView) findViewById(R.id.txt_record);
 //录音显示的控件
 initVoice();

// wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
// .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

 //键盘
 initKeyboard();

 }

 //录音显示的控件
 private void initVoice() {

 layout_voice = (RelativeLayout) findViewById(R.id.layout_voice);
 img_im_microphone_state = (ImageView) findViewById(R.id.img_im_microphone_state);
 img_im_microphone_sound_size = (ImageView) findViewById(R.id.img_im_microphone_sound_size);
 txt_im_microphone_show_text = (TextView) findViewById(R.id.txt_im_microphone_show_text);

 }

 private void initKeyboard() {

 //输入框栏 用来判断软键盘是否弹出
 keyboardListenRelativeLayout = (KeyboardListenRelativeLayout) findViewById(R.id.keyboardListenRelativeLayout);
 layout_expression = (RelativeLayout) findViewById(R.id.layout_expression);
 viewPager = (ViewPager) findViewById(R.id.viewPager);
 viewPoints = (LinearLayout) findViewById(R.id.viewGroup);
 img_voice = (ImageView) findViewById(R.id.img_voice);
 img_expression = (ImageView) findViewById(R.id.img_expression);
 img_other = (ImageView) findViewById(R.id.img_other);
 layout_other = (RelativeLayout) findViewById(R.id.layout_other);

 //照片
 im_chat_poto = (ImageView) findViewById(R.id.im_chat_poto);
 // 拍摄
 im_chat_camera = (ImageView) findViewById(R.id.im_chat_camera);
 // 小视频
 im_chat_video = (ImageView) findViewById(R.id.im_chat_video);
 // 位置
 im_chat_location = (ImageView) findViewById(R.id.im_chat_location);

 //宽度高度适配 6
 WindowManager wm = ChatActivity.this.getWindowManager();
 int width = wm.getDefaultDisplay().getWidth();
 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
 layoutParams.width = (width - PixelOrdpManager.dip2px(getbaseContext(), 16 * 5)) / 4;
 layoutParams.height = (width - PixelOrdpManager.dip2px(getbaseContext(), 16 * 5)) / 4;
 layoutParams.leftMargin = PixelOrdpManager.dip2px(getbaseContext(), 16);
 im_chat_poto.setLayoutParams(layoutParams);
 im_chat_camera.setLayoutParams(layoutParams);
 im_chat_video.setLayoutParams(layoutParams);
 im_chat_location.setLayoutParams(layoutParams);


 //加载表情的
 initViewPager();

 //显示录音图标
 img_voice.setImageResource(R.mipmap.im_chat_voice);
 //显示表情图标
 img_expression.setImageResource(R.mipmap.emoji_bw);
 //显示其他图标
 img_other.setImageResource(R.mipmap.im_chat_add_normal);

 }


 private void initData() {
 intent = getIntent();
 if (intent.getSerializableExtra("mbUserModel") != null) {
 mbUserModel = (MBUserModel) intent.getSerializableExtra("mbUserModel");
 meMBUserModel= MBUserManager.getInstance().getMBUser(LoginManager.userid);
 txt_im_object_name.setText(mbUserModel.getNickname());

// chatAdapter = new ChatAdapter();
// listView.setAdapter(chatAdapter);
 }

 }

 private void initListener() {
 //返回
 findViewById(R.id.img_finish).setonClickListener(new View.onClickListener() {
 @Override
 public void onClick(View v) {
 SoftKeyboardManager.HideSoftKeyboard(v);
 finish();
 }
 });


 //键盘的点击事件
 initKeyboardListener();



// //播放语音
// findViewById(R.id.txt_start).setonClickListener(new View.onClickListener() {
// @Override
// public void onClick(View v) {
//
// mPlayer = new MediaPlayer();
// try{
//  mPlayer.setDataSource(FileName);
//  mPlayer.prepare();
//  mPlayer.start();
// }catch(IOException e){
//  Log.e("ChatActivity","播放失败");
// }
//
// }
// });
 }

 
 public static boolean isExitsSdcard() {
 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
 return true;
 else
 return false;
 }

// private PowerManager.WakeLock wakeLock;

 
 //语音操作对象
 private MediaPlayer mPlayer = null;
 private MediaRecorder mRecorder = null;
 //语音文件保存路径
 private String FileName = null;
 class PressToSpeakListen implements View.onTouchListener {
 @SuppressLint({"ClickableViewAccessibility", "Wakelock"})
 @Override
 public boolean onTouch(View v, MotionEvent event) {
 switch (event.getAction()) {
 case MotionEvent.ACTION_DOWN:
  //语音的显示
  layout_voice.setVisibility(View.VISIBLE);
  //语音按钮点下
  txt_record.setText("松开结束");
  txt_record.setBackgroundResource(R.drawable.shape_im_chat_voice_down);

  if (!isExitsSdcard()) {
  Toast.makeText(ChatActivity.this, "发送语音需要sdcard支持!",
  Toast.LENGTH_SHORT).show();
  return false;
  }
//  try {
//  v.setPressed(true);
////  wakeLock.acquire();
////  if (VoicePlayClickListener.isPlaying)
////  VoicePlayClickListener.currentPlayListener
////   .stopPlayVoice();
////  recordingContainer.setVisibility(View.VISIBLE);
////  recordingHint
////  .setText(getString(R.string.move_up_to_cancel));
////  recordingHint.setBackgroundColor(Color.TRANSPARENT);
////  voiceRecorder.startRecording(null, toChatUsername,
////  getApplicationContext());
//  } catch (Exception e) {
//  e.printStackTrace();
//  v.setPressed(false);
////  if (wakeLock.isHeld())
////  wakeLock.release();
////  if (voiceRecorder != null)
////  voiceRecorder.discardRecording();
////  recordingContainer.setVisibility(View.INVISIBLE);
////  Toast.makeText(ChatActivity.this, R.string.recoding_fail,
////  Toast.LENGTH_SHORT).show();
//  return false;
//  }
  //设置sdcard的路径
  FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
  FileName += "/audiorecordtest.3gp";
  mRecorder = new MediaRecorder();
  mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  mRecorder.setOutputFile(FileName);
  mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  try {
  mRecorder.prepare();
  } catch (IOException e) {
  Log.e("ChatActivity", "prepare() failed");
  }
  mRecorder.start();


  return true;
 case MotionEvent.ACTION_MOVE: {
  if (event.getY() < 0) {
  txt_im_microphone_show_text.setText("松指取消发送");

//  txt_record.setText("松开结束");
//  txt_record.setBackgroundResource(R.drawable.shape_im_chat_voice_down);
  } else {
  txt_im_microphone_show_text.setText("上滑取消发送");

//  txt_record.setText("按住说话");
//  txt_record.setBackgroundResource(R.drawable.shape_im_chat_voice_up);
  }
  return true;
 }
 case MotionEvent.ACTION_UP:
  //语音的显示
  layout_voice.setVisibility(View.GONE);
  //语音按钮点下
  txt_record.setText("按住说话");
  txt_record.setBackgroundResource(R.drawable.shape_im_chat_voice_up);

//  v.setPressed(false);
////  recordingContainer.setVisibility(View.INVISIBLE);
////  if (wakeLock.isHeld())
////  wakeLock.release();
//  if (event.getY() < 0) {
//  // discard the recorded audio.
////  voiceRecorder.discardRecording();
//
//  } else {
//  // stop recording and send voice file
////  try {
////  int length = voiceRecorder.stopRecoding();
////  if (length > 0) {
////  sendVoice(voiceRecorder.getVoiceFilePath(),
////   voiceRecorder
////   .getVoiceFileName(toChatUsername),
////   Integer.toString(length), false);
////  } else if (length == EMError.INVALID_FILE) {
////  Toast.makeText(getApplicationContext(), "无录音权限",
////   Toast.LENGTH_SHORT).show();
////  } else {
////  Toast.makeText(getApplicationContext(), "录音时间太短",
////   Toast.LENGTH_SHORT).show();
////  }
////  } catch (Exception e) {
////  e.printStackTrace();
////  Toast.makeText(ChatActivity.this, "发送失败,请检测服务器是否连接",
////   Toast.LENGTH_SHORT).show();
////  }
//
//  }

  mRecorder.stop();
  mRecorder.release();
  mRecorder = null;

  return true;
 default:
//  recordingContainer.setVisibility(View.INVISIBLE);
//  if (voiceRecorder != null)
//  voiceRecorder.discardRecording();
  return false;
 }
 }
 }


 private void initKeyboardListener() {

 //录音的点击
 txt_record.setonTouchListener(new PressToSpeakListen());

 //照片
 im_chat_poto.setonClickListener(new View.onClickListener() {
 @Override
 public void onClick(View v) {

 Intent intent = new Intent();
 intent.setType("image

 private void initMap(Bundle savedInstanceState) {
 scrollView_location_bitmap= (ScrollView) findViewById(R.id.scrollView_location_bitmap);
 img_location_map= (ImageView) findViewById(R.id.img_location_map);
 mapView = (MapView) findViewById(R.id.map_location);
 mapView.onCreate(savedInstanceState);
 if (aMap == null) {
 aMap = mapView.getMap();
 }
 UiSettings mUiSettings = aMap.getUiSettings();
 mUiSettings.setZoomControlsEnabled(false);// 是否显示放大缩小按钮
 mUiSettings.setMyLocationButtonEnabled(false);// 是否显示定位按钮
 mUiSettings.setCompassEnabled(false);// 是否显示指南针
 mUiSettings.setScaleControlsEnabled(false); // 是否显示比例尺
 mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// logo位置
 
 setMyLocationStyle();
 
 aMap.setLocationSource(this);
 aMap.setMyLocationEnabled(true);
 aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
 aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
 getLocation();
 //准确位置获取
 geocodeSearch = new GeocodeSearch(ChatActivity.this);
 geocodeSearch.setonGeocodeSearchListener(ChatActivity.this);
 getAddress(latLonPoint);
 
 aMap.setonMapLoadedListener(new AMap.onMapLoadedListener() {
 @Override
 public void onMapLoaded() {
 
 aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
 aMap.showMapText(true);
 aMap.showIndoorMap(false);

 //移动地图
 aMap.setonCameraChangeListener(new AMap.onCameraChangeListener() {
  @Override
  public void onCameraChange(CameraPosition cameraPosition) {

  }

  @Override
  public void onCameraChangeFinish(CameraPosition cameraPosition) {
  if(isFirst==false){
  // 获取当前地图中心点的坐标
  mTarget = aMap.getCameraPosition().target;
//  currentlatLng=mTarget;
  //准确位置获取
  geocodeSearch = new GeocodeSearch(ChatActivity.this);
  geocodeSearch.setonGeocodeSearchListener(ChatActivity.this);
  latLonPoint = new LatLonPoint(mTarget.latitude, mTarget.longitude);
  getAddress(latLonPoint);
  isFirst=true;
  //第一次定位移动到定位点作为地图的中心点
  if(isShowMoveLocationCenter==true){
  aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
  isShowMoveLocationCenter=false;
  }

  }

  }
 });

 }
 });
 }

 
 private void setMyLocationStyle() {
 MyLocationStyle myLocationStyle = new MyLocationStyle();// 自定义系统定位小蓝点
 myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.o_map));// 设置小蓝点的图标
 myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
 myLocationStyle.radiusFillColor(Color.TRANSPARENT);// 设置圆形的填充颜色
 myLocationStyle.anchor(0.5f, 0.5f);// 设置小蓝点的锚点
 myLocationStyle.strokeWidth(0);// 设置圆形的边框粗细
 aMap.setMyLocationStyle(myLocationStyle);
 }

 private void getLocation() {
 //经纬度获取
 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 List providers = locationManager.getProviders(true);
 if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
 locationProvider = LocationManager.NETWORK_PROVIDER;
 } else if (providers.contains(LocationManager.GPS_PROVIDER)) {//GPS的定位放在第一个 得不到数据
 locationProvider = LocationManager.GPS_PROVIDER;
 } else {
 return;
 }
 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
 return;
 }
 location = locationManager.getLastKnownLocation(locationProvider);
 if (location != null) {
 ShowLocation(location);
 latLonPoint = new LatLonPoint(location.getLatitude(), location.getLongitude());
 } else {

 }
 locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);

 }

 LocationListener locationListener = new LocationListener() {
 @Override
 public void onLocationChanged(Location location) {
 ShowLocation(location);
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {

 }

 @Override
 public void onProviderEnabled(String provider) {

 }

 @Override
 public void onProviderDisabled(String provider) {

 }
 };


 private void ShowLocation(Location location) {
 latitude = location.getLatitude();
 longitude = location.getLongitude();
 }

 @Override
 public void activate(onLocationChangedListener onLocationChangedListener) {
 mListener = onLocationChangedListener;
 if (mLocationClient == null) {
 mLocationClient = new AMapLocationClient(MBUtil.getContext());
 AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
 mLocationClient.setLocationListener(this);
 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
 mLocationClient.setLocationOption(mLocationOption);
 mLocationClient.startLocation();
 }
 }

 @Override
 public void deactivate() {
 mListener = null;
 if (mLocationClient != null) {
 mLocationClient.stopLocation();
 mLocationClient.onDestroy();
 }
 mLocationClient = null;
 }

 @Override
 public void onLocationChanged(AMapLocation aMapLocation) {
 if (mListener != null && aMapLocation != null) {
 if (aMapLocation.getErrorCode() == 0) {
 mListener.onLocationChanged(aMapLocation);// 显示系统蓝点

 latitude = aMapLocation.getLatitude();// 纬度
 longitude = aMapLocation.getLongitude();// 经度
 // TODO: 2016/6/2
 } else {
 String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
 System.out.println(errText);
 }
 } else {


 }
 }

 @Override
 public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

 if (rCode == 1000) {
 if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {

 String province = result.getRegeocodeAddress().getProvince();
 String district = result.getRegeocodeAddress().getDistrict();
 String township = result.getRegeocodeAddress().getTownship();
 String neighborhood = result.getRegeocodeAddress().getNeighborhood();

 //当前具体位置
 currentSpecificPosition = result.getRegeocodeAddress().getFormatAddress();

 } else {
 Toast.makeText(ChatActivity.this, "定位失败,请重试", Toast.LENGTH_SHORT);
 }
 } else if (rCode == 27) {
 Toast.makeText(ChatActivity.this, "定位失败,请重试", Toast.LENGTH_SHORT);
 } else if (rCode == 32) {
 Toast.makeText(ChatActivity.this, "定位失败,请重试", Toast.LENGTH_SHORT);
 } else {
 Toast.makeText(ChatActivity.this, "定位失败,请重试", Toast.LENGTH_SHORT);
 }

 }

 @Override
 public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

 }
 
 public void getAddress(final LatLonPoint latLonPoint) {
 RegeocodeQuery regeocodeQuery = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
 geocodeSearch.getFromLocationAsyn(regeocodeQuery);
 }

 
 public static Bitmap getBitmapByView(ScrollView scrollView) {
 int h = 0;
 Bitmap bitmap = null;

 for (int i = 0; i < scrollView.getChildCount(); i++) {
 h += scrollView.getChildAt(i).getHeight();
 scrollView.getChildAt(i).setBackgroundResource(R.mipmap.riding_report);
// scrollView.getChildAt(i).setBackgroundColor(
//  Color.parseColor("0xFFFFFFFF"));
 }

 bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
 Bitmap.Config.RGB_565);
 final Canvas canvas = new Canvas(bitmap);
 scrollView.draw(canvas);
 return bitmap;
 }

 
 public static String savePic(Bitmap b) {
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
 Locale.US);
 File outfile = new File("/sdcard/image");
 // 如果文件不存在,则创建一个新文件
 if (!outfile.isDirectory()) {
 try {
 outfile.mkdir();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 String fname = outfile + "/" + sdf.format(new Date()) + ".png";
 FileOutputStream fos = null;
 try {
 fos = new FileOutputStream(fname);
 if (null != fos) {
 b.compress(Bitmap.CompressFormat.PNG, 90, fos);
 fos.flush();
 fos.close();
 }
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 return fname;
 }

 public static final int CHOOSE_IMAGE = 3;
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {


 if (requestCode == CameraConstants.REQUEST_TAKE && resultCode == Activity.RESULT_OK) {

 Log.d("ChatActivity", "imageUri:" + imageUri);
// Picasso.with(ChatActivity.this).load(imageUri).into(img_bitmap);
// Intent intent = new Intent(this, CropPhotoActivity.class);
// intent.setData(imageUri);
// intent.putExtra("exist", true);
// startActivityForResult(intent, CHOOSE_IMAGE);
 }

 if (requestCode == CameraConstants.REQUEST_PICK && resultCode == Activity.RESULT_OK) {

// Picasso.with(ChatActivity.this).load(data.getData()).into(img_bitmap);
 Log.d("ChatActivity", "data.getData():" + data.getData());

// Uri uri = data.getData();
// Intent intent = new Intent(this, CropPhotoActivity.class);
// intent.setData(uri);
// intent.putExtra("exist", true);
// startActivityForResult(intent, CHOOSE_IMAGE);
 }

 //纯照片
// if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK) {
// picStringUrl = data.getStringExtra("filePath");
// Log.d("ChatActivity", picStringUrl);
//
// }
 super.onActivityResult(requestCode, resultCode, data);
 }


}

闲暇之余把相册选取照片,拍摄也给大家提供了,另外我基于高德地图把位置的获取也做了(位置的照片,照片的路径,位置的描述及经纬度都获取了,大家可以自行借鉴,选取自己所需的)

Android 仿微信的键盘切换Demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/154676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号