@Override
public void layout(int l, int t, int r, int b) {
if (mIsCrop && l == 0 && t == 0) {
float scaleRatio = 1.0F;
float defaultRatio = 1.0F;
if (mIsWidthLarger) {
// 高度为原高度 3/4 居中
scaleRatio = defaultRatio + defaultRatio / 4F;
} else {
// 宽度为原宽度 3/4 居中
scaleRatio = defaultRatio - defaultRatio / 4F;
}
int width = r - l;
int height = b - t;
if (scaleRatio > defaultRatio) {
int offsetY = (int) (height * (scaleRatio - defaultRatio) / 2F);
// 除了2 上加下减 改变高度显示区域
t += offsetY;
b -= offsetY;
} else if (scaleRatio < defaultRatio) {
int offsetX = (int) (width * (defaultRatio - scaleRatio) / 2F);
// 左加右减 改变宽度显示区域
l += offsetX;
r -= offsetX;
}
}
super.layout(l, t, r, b);
}
// 图片缓存
private LruCache<String, Bitmap> mLruCache;
// 根据实际情况 设置 maxSize 大小
mLruCache = new LruCache<>(Integer.MAX_VALUE);
/**
* @param path 图片地址
*/
public synchronized void setImagePath(String path) {
if (path != null && !path.equals("")) {
Bitmap lruBitmap = mLruCache.get(path);
if (lruBitmap == null) {
// 图片压缩
Bitmap bitmap = BitmapUtils.getCompressBitmap(getContext(), path);
mLruCache.put(path, bitmap);
lruBitmap = bitmap;
}
if (lruBitmap != null) {
mFirstLayout = true;
mMaxScale = 3.0F;
// 根据实际情况改变留白裁切状态
setImageBitmap(lruBitmap);
onGlobalLayout();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
// 重置数据 由于篇幅原因 省略相应代码 ......
break;
case MotionEvent.ACTION_MOVE:
// y 相对于 RecyclerView y坐标
float y = e.getY();
measureRecyclerHeight(y);
if (mLastRawY == 0) {
mLastRawY = e.getRawY();
}
mDeltaRawY = mLastRawY - e.getRawY();
if (mIsExpand) {
// 展开
mListener.onScroll(y, mDeltaRawY, mMaxParentScrollRange);
} else {
// 收起 canScrollVertically 判定是否滑动到底部
if (!mIsConsumeTouchEvent && !canScrollVertically(-1)) {
mIsConsumeTouchEvent = true;
}
if (mIsConsumeTouchEvent && mDeltaRawY != 0) {
mListener.onScroll(y, mDeltaRawY, mMaxParentScrollRange);
}
}
// 处于非临界状态
mIsConsumeTouchEvent = mCurrentParenScrollY > 0 & mCurrentParenScrollY < mMaxParentScrollRange;
mVelocityTracker.addMovement(e);
mLastRawY = e.getRawY();
if (y < 0 || mIsConsumeTouchEvent) {
return false;
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// 重置数据
resetData();
mLastRawY = 0;
// 处理滑动速度
mVelocityTracker.addMovement(e);
mVelocityTracker.computeCurrentVelocity(1000);
int velocityY = (int) Math.abs(mVelocityTracker.getYVelocity());
mListener.onFiling(mDeltaRawY > 0 ? -velocityY : velocityY);
mDeltaRawY = 0;
y = e.getY();
if (y < 0) {
return false;
}
break;
}
return super.onTouchEvent(e);
}
/**
* 开始滚动
*
* @param isExpand 是否展开
*/
private void startScroll(boolean isExpand) {
mIsExpand = isExpand;
if (mListener != null) {
mListener.isExpand(isExpand);
if (mIsExpand) {
// 必须保证滚动完成 再触发回调
postDelayed(new Runnable() {
@Override
public void run() {
mListener.completeExpand();
}
}, SCROLL_DURATION);
}
}
if (!mOverScroller.isFinished()) {
mOverScroller.abortAnimation();
}
int dy = isExpand ? -getScrollY() : mScrollRange - getScrollY();
// SCROLL_DURATION = 500
mOverScroller.startScroll(0, getScrollY(), 0, dy, SCROLL_DURATION);
postInvalidate();
}
/**
* @param recyclerView
* @param touchX
* @param touchY
*/
public void handlerRecyclerInvalidClick(RecyclerView recyclerView, int touchX, int touchY) {
if (recyclerView != null && recyclerView.getChildCount() > 0) {
for (int i = 0; i < recyclerView.getChildCount(); i++) {
View childView = recyclerView.getChildAt(i);
if (childView != null) {
if (childView != null && isTouchView(touchX, touchY, childView)) {
childView.performClick();
return;
}
}
}
}
}
// 触摸点是否view区域内
private boolean isTouchView(int touchX, int touchY, View view) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
return rect.contains(touchX, touchY);
}
# -*- coding: utf-8 -*-
"""
功能:百度翻译
注意事项:中英文自动切换
"""
import requests
import re
class Baidu_Translate(object):
def __init__(self, query_string):
self.query_string = query_string
self.url_1 = 'https://fanyi.baidu.com/sug'
# self.url = 'https://fanyi.baidu.com/v2transapi' # 这里不能用这个地址,因为对方采用了反爬虫措施,访问这个地址是人家是不会给你任何数据的
self.url_0 = 'https://fanyi.baidu.com/transapi'
self.zh_pattern = re.compile('[\u4e00-\u9fa5]+')
self.headers = {
'Accept': '* / *',
'Accept - Encoding': 'gzip, deflate',
'Accept - Language': 'zh-CN, zh; q=0.9',
'Connection': 'keep - alive',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
def get_post_data(self):
"""
拿到 post 请求上传的参数,并判断输入类型并予以返回
:return: 查询词
"""
if re.search(pattern=self.zh_pattern, string=self.query_string): # 输入的内容含有中文,则判别其为中文输入
return {
"from": "zh",
"to": "en",
"kw": self.query_string, # 模糊查询 url_1关键词
"query": self.query_string, # 精准查询 url_0关键词
}
else:
return {
"from": "en",
"to": "zh",
"kw": self.query_string, # 模糊查询 url_1关键词
"query": self.query_string, # 精准查询 url_0关键词
}
def request_translate(self):
"""
向百度请求 json 数据
:return: 向百度请求的 json 数据
"""
data = self.get_post_data()
try:
response_0 = requests.request(method="post", url=self.url_0, headers=self.headers, data=data).json()
except Exception: # 进行数据请求的任何异常处理
response_0 = ''
try:
response_1 = requests.request(method="post", url=self.url_1, headers=self.headers, data=data).json()
except Exception: # 进行数据请求的任何异常处理
response_1 = ''
return response_0, response_1
def parse_translate_data(self):
"""
数据解析,将请求到的翻译内容解析并输出
:return: None
"""
response_0 = self.request_translate()[0]
response_1 = self.request_translate()[1]
# item = response_0
if response_0:
item = response_0.get('data')[0].get('dst')
print('key word:', self.query_string, '\t', 'translate:', item)
if response_1:
data = response_1.get('data')
print()
for item in data[:1]: # 长度一般为5,这里只保留其释义
print('key word: \t[ {key} ]'.format(key=item.get('k')))
print('value: \t\t[ {value} ]'.format(value=item.get('v')))
print()
# print(response_1.get('data'))
def main():
"""
主函数
:return: None
"""
while True:
try:
query_keywords = input("""请输入您要翻译的内容 [ 输入四个'0'退出 ] : """)
if query_keywords == "0000": # 如果输入四个 '0',退出小程序
print('########## 您已成功退出百度翻译 ##########')
break
else:
baidu = Baidu_Translate(query_string=query_keywords)
baidu.parse_translate_data()
except Exception as e:
print('请求出错,请重试', e.args)
if __name__ == '__main__':
main()
try {
showAskDialog();//对应弹框逻辑方法
}
catch (Exception e)
{
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, GET_DIALOG_PERMISSION);//GET_DIALOG_PERMISSION为预先定义好的返回结果常量
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GET_DIALOG_PERMISSION)//GET_DIALOG_PERMISSION为预先定义好的返回结果常量
{
showAskDialog();//对应弹框逻辑方法
}
}
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SSID:"
android:textColor="@android:color/black"
android:textSize="30sp" />
<TextView
android:id="@+id/wifiSSID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/textView1"
android:text="-"
android:textColor="@android:color/black"
android:textSize="30sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="信号强度"
android:layout_below="@id/textView1"
android:textColor="@android:color/black"
android:textSize="30sp" />
<ImageView
android:id="@+id/ivWifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView2"
android:background="@drawable/wifi1"/>
</RelativeLayout>//WXSDKEngine的init方法已经被弃用,weex的初始化需要使用下面这个initialize方法
public static void initialize(Application application,InitConfig config){
synchronized (mLock) {
//如果已经初始化过那么直接return
if (mIsInit) {
return;
}
long start = System.currentTimeMillis();
WXEnvironment.sSDKInitStart = start;
if(WXEnvironment.isApkDebugable()){
WXEnvironment.sLogLevel = LogLevel.DEBUG;
}else{
if(WXEnvironment.sApplication != null){
WXEnvironment.sLogLevel = LogLevel.WARN;
}else {
WXLogUtils.e(TAG,"WXEnvironment.sApplication is " + WXEnvironment.sApplication);
}
}
doInitInternal(application,config);
WXEnvironment.sSDKInitInvokeTime = System.currentTimeMillis()-start;
WXLogUtils.renderPerformanceLog("SDKInitInvokeTime", WXEnvironment.sSDKInitInvokeTime);
//监测weex表现的的一个检测器的初始化
WXPerformance.init();
mIsInit = true;
}
}private static void doInitInternal(final Application application,final InitConfig config){
//这里给WXEnvironment中的application赋值,方便后续使用
WXEnvironment.sApplication = application;
if(application == null){//application为空的话报错
WXLogUtils.e(TAG, " doInitInternal application is null");
WXExceptionUtils.commitCriticalExceptionRT(null,
WXErrorCode.WX_KEY_EXCEPTION_SDK_INIT,
"doInitInternal",
WXErrorCode.WX_KEY_EXCEPTION_SDK_INIT.getErrorMsg() + "WXEnvironment sApplication is null",
null);
}
//weex环境初始化标识设置为false
WXEnvironment.JsFrameworkInit = false;
//通过单例模式获取一个WXBridgeManager的唯一实例,使用WXBridgeManager开启一个安全的线程初始化weex框架。
//开启安全线程的细节暂时不深究,这里主要看weex框架的初始化流程
WXBridgeManager.getInstance().post(new Runnable() {
@Override
public void run() {
//开始初始化时间
long start = System.currentTimeMillis();
//获取WXSDKManager实例
WXSDKManager sm = WXSDKManager.getInstance();
//使用sm监听weex框架初始化,我们可以通过WXSDKManager.registerStatisticsListener()
//注册一个监听器
sm.onSDKEngineInitialize();
//设置weex框架配置项
if(config != null ) {
sm.setInitConfig(config);
}
//初始化so文件加载器,后两个参数分别为初始化时的加载器和监听器。
WXSoInstallMgrSdk.init(application,
sm.getIWXSoLoaderAdapter(),
sm.getWXStatisticsListener());
//加载so库文件,如不设置自定义的IWXSoLoaderAdapter,那么采用系统默认方式加载
boolean isSoInitSuccess = WXSoInstallMgrSdk.initSo(V8_SO_NAME, 1, config!=null?config.getUtAdapter():null);
if (!isSoInitSuccess) {//加载失败报错
WXExceptionUtils.commitCriticalExceptionRT(null,
WXErrorCode.WX_KEY_EXCEPTION_SDK_INIT,
"doInitInternal",
WXErrorCode.WX_KEY_EXCEPTION_SDK_INIT.getErrorMsg() + "isSoInit false",
null);
return;
}
//使用WXSDKManager初始化jsFramwork,就是讲weexSdk中assets下的js文件拷贝到缓存目录中,使用so的native方法执行
sm.initScriptsFramework(config!=null?config.getFramework():null);
//计算初始化所用时间
WXEnvironment.sSDKInitExecuteTime = System.currentTimeMillis() - start;
WXLogUtils.renderPerformanceLog("SDKInitExecuteTime", WXEnvironment.sSDKInitExecuteTime);
}
});
//注册weexSDK内置的一系列Component和Module
register();
}
public static synchronized boolean registerComponent(final String type, final IFComponentHolder holder, final Map<String, Object> componentInfo) throws WXException {
if (holder == null || TextUtils.isEmpty(type)) {
return false;
}
//execute task in js thread to make sure register order is same as the order invoke register method.
//在js线程执行这个注册组件的任务,以确保我们注册组件的顺序与调用注册方法的顺序一致。
WXBridgeManager.getInstance()
.post(new Runnable() {
@Override
public void run() {
try {
Map<String, Object> registerInfo = componentInfo;
if (registerInfo == null){
registerInfo = new HashMap<>();
}
//设置注册信息
registerInfo.put("type",type);
//holder是之前让大家留意的SimpleComponentHolder类
registerInfo.put("methods",holder.getMethods());
//生成原生组件映射
registerNativeComponent(type, holder);
//将组件注册信息传递到jsFramwork,生成js中解析vue中原生component是所需的Json映射
registerJSComponent(registerInfo);
//sComponentInfos是js解析需要使用的类,包含所有组件的注册信息
sComponentInfos.add(registerInfo);
} catch (WXException e) {
WXLogUtils.e("register component error:", e);
}
}
});
return true;
}