提交 997de49f 编写于 作者: 门心叼龙's avatar 门心叼龙

init commit

上级
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="D:/soft/android/gradle/gradle-4.1" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EclipseCodeFormatter">
<option name="defaultSettings" value="true" />
<option name="formatter" value="ECLIPSE" />
<option name="id" value="1493019106702" />
<option name="name" value="default" />
<option name="pathToConfigFileJava" value="D:/soft/android/eclipse-google-code-style.xml" />
<option name="selectedJavaProfile" value="GoogleStyle" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/yigetranslate.iml" filepath="$PROJECT_DIR$/yigetranslate.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="D:\workspace\yigetranslate\yicheng" vcs="Git" />
</component>
</project>
\ No newline at end of file
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId 'com.yige.translate'
minSdkVersion 14
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.google.dagger:dagger:2.13'
annotationProcessor 'com.google.dagger:dagger-compiler:2.13'
}
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
package com.yige.translate;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.yige.traslate", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yige.translate">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ui.activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".ui.activity.SecondActivity"
android:label="@string/title_activity_second"
android:theme="@style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
\ No newline at end of file
package com.yige.translate;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import com.yige.translate.injection.component.AppComponent;
import com.yige.translate.injection.component.DaggerAppComponent;
import com.yige.translate.injection.module.APIModule;
import com.yige.translate.injection.module.AppModule;
/**
* Created by gxl on 2017/11/28.
*/
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private static AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this))
.aPIModule(new APIModule()).build();
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
Log.v(TAG,"onActivityCreated start...");
}
@Override
public void onActivityStarted(Activity activity) {
Log.v(TAG,"onActivityStarted start...");
}
@Override
public void onActivityResumed(Activity activity) {
Log.v(TAG,"onActivityResumed start...");
}
@Override
public void onActivityPaused(Activity activity) {
Log.v(TAG,"onActivityPaused start...");
}
@Override
public void onActivityStopped(Activity activity) {
Log.v(TAG,"onActivityStopped start...");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
Log.v(TAG,"onActivitySaveInstanceState start...");
}
@Override
public void onActivityDestroyed(Activity activity) {
Log.v(TAG,"onActivityDestroyed start...");
}
});
}
public static AppComponent getAppComponent() {
return mAppComponent;
}
}
package com.yige.translate.injection;
import javax.inject.Scope;
/**
* Created by gxl on 2017/11/28.
*/
@Scope
public @interface ActivityScope {
}
package com.yige.translate.injection.component;
import com.yige.translate.MyApplication;
import com.yige.translate.injection.module.APIModule;
import com.yige.translate.injection.module.AppModule;
import com.yige.translate.mvp.model.BaiduAPI;
import com.yige.translate.mvp.model.YoudaoAPI;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by gxl on 2017/11/28.
*/
@Singleton
@Component(modules = {AppModule.class, APIModule.class})
public interface AppComponent {
MyApplication getMyApplication();
BaiduAPI getBaiduAPI();
YoudaoAPI getYouDaoAPI();
}
package com.yige.translate.injection.component;
import com.yige.translate.injection.ActivityScope;
import com.yige.translate.injection.module.MainModule;
import com.yige.translate.mvp.model.BaiduModel;
import com.yige.translate.ui.activity.MainActivity;
import dagger.Component;
/**
* Created by gxl on 2017/11/28.
*/
@ActivityScope
@Component(modules = {MainModule.class} ,dependencies = {AppComponent.class})
public interface MainComponent {
void inject(MainActivity activity);
//BaiduModel getBaiduModel();
}
package com.yige.translate.injection.module;
import com.yige.translate.injection.ActivityScope;
import com.yige.translate.mvp.model.BaiduAPI;
import com.yige.translate.mvp.model.YoudaoAPI;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by gxl on 2017/11/28.
*/
@Module
public class APIModule {
@Singleton
@Provides
BaiduAPI providerBaiduAPI() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://api.fanyi.baidu.com/api/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create()).build();
return retrofit.create(BaiduAPI.class);
}
@Singleton
@Provides
YoudaoAPI providerYoudaoAPI() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://openapi.youdao.com/api/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create()).build();
return retrofit.create(YoudaoAPI.class);
}
}
package com.yige.translate.injection.module;
import com.yige.translate.MyApplication;
import javax.inject.Singleton;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
/**
* Created by gxl on 2017/11/28.
*/
@Module
public class AppModule {
private MyApplication mApplication;
public AppModule(MyApplication application) {
mApplication = application;
}
@Singleton
@Provides
MyApplication providerMyApplication(){
return mApplication;
}
}
/**
* Copyright 2017 JessYan
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.yige.translate.injection.module;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import com.yige.translate.injection.ActivityScope;
import com.yige.translate.mvp.model.BaiduAPI;
import com.yige.translate.mvp.model.BaiduModel;
import com.yige.translate.mvp.model.IBaiduModel;
import com.yige.translate.mvp.model.ITranslateService;
import com.yige.translate.mvp.model.IYoudaoModel;
import com.yige.translate.mvp.model.TranslateService;
import com.yige.translate.mvp.model.YoudaoAPI;
import com.yige.translate.mvp.model.YoudaoModel;
import com.yige.translate.mvp.presenter.BaiduContract;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class MainModule {
public static final String TAG = MainModule.class.getSimpleName();
private BaiduContract.View view;
public MainModule(BaiduContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
BaiduContract.View provideBaiduView() {
return this.view;
}
@ActivityScope
@Provides
IBaiduModel provideBaiduModel(BaiduModel model) {
return model;
}
@ActivityScope
@Provides
IYoudaoModel provideYoudaoModel(YoudaoModel model) {
return model;
}
@ActivityScope
@Provides
ITranslateService providerTranslateService(TranslateService translateService){
return translateService;
}
// @ActivityScope
// @Provides
// BaiduAPI providerBaiduAPI() {
// Log.v(TAG,"providerBaiduAPI start...");
// Retrofit retrofit = new Retrofit.Builder().baseUrl("http://api.fanyi.baidu.com/api/")
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create()).build();
// return retrofit.create(BaiduAPI.class);
// }
// @ActivityScope
// @Provides
// YoudaoAPI providerYoudaoAPI() {
// Log.v(TAG,"providerYoudaoAPI start...");
// Retrofit retrofit = new Retrofit.Builder().baseUrl("http://openapi.youdao.com/api/")
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create()).build();
// return retrofit.create(YoudaoAPI.class);
// }
// @ActivityScope
// @Provides
// BaiduModel providerBaiduModel(){
// return new BaiduModel(providerBaiduAPI());
// }
}
package com.yige.translate.mvp.model;
import com.yige.translate.mvp.model.bean.TransResult;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Created by gxl on 2017/11/26.
*/
public interface BaiduAPI {
@GET("trans/vip/translate?")
Observable<ResponseBody> translate(@Query("q") String q, @Query("from") String from,
@Query("to") String to, @Query("appid") String appid, @Query("salt") String salt,
@Query("sign") String sign);
@GET("trans/vip/translate?")
Observable<TransResult> translate(@QueryMap Map<String, String> map);
}
package com.yige.translate.mvp.model;
import com.yige.translate.injection.ActivityScope;
import com.yige.translate.mvp.model.baidu.MD5;
import com.yige.translate.mvp.model.bean.TransResult;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import io.reactivex.Observable;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by gxl on 2017/11/26.
*/
public class BaiduModel implements IBaiduModel {
public static final String appid = "20171126000099472";
public static final String securityKey = "adIVJdw755SB83oq0Is0";
private final BaiduAPI mBaiduService;
@Inject
public BaiduModel(BaiduAPI baiduAPI) {
mBaiduService = baiduAPI;
}
@Override
public Observable<TransResult> translate1(String query, String from, String to) {
return mBaiduService.translate(buildParams(query, from, to));
}
public Map<String, String> buildParams(String query, String from, String to) {
Map<String, String> params = new HashMap<String, String>();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("appid", appid);
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
params.put("salt", salt);
// 签名
String src = appid + query + salt + securityKey; // 加密前的原文
params.put("sign", MD5.md5(src));
return params;
}
}
package com.yige.translate.mvp.model;
import com.yige.translate.mvp.model.bean.TransResult;
import io.reactivex.Observable;
/**
* Created by gxl on 2017/11/26.
*/
public interface IBaiduModel extends IBaseModel{
/**
*
* @param query,
* @param from
* @param to
* @return
*/
Observable<TransResult> translate1(String query, String from, String to);
}
package com.yige.translate.mvp.model;
/**
* Created by gxl on 2017/11/27.
*/
public interface IBaseModel {
}
package com.yige.translate.mvp.model;
/**
* Created by gxl on 2017/11/28.
*/
public interface ITranslateService {
IBaiduModel getBaiduModel();
IYoudaoModel getYouDaoModel();
}
package com.yige.translate.mvp.model;
import com.yige.translate.mvp.model.bean.TransResult;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
/**
* Created by gxl on 2017/11/26.
*/
public interface IYoudaoModel extends IBaseModel{
/**
*
* @param query,
* @param from
* @param to
* @return
*/
Observable<ResponseBody> translate1(String query, String from, String to);
}
package com.yige.translate.mvp.model;
import javax.inject.Inject;
/**
* Created by gxl on 2017/11/28.
*/
public class TranslateService implements ITranslateService {
private BaiduModel mBaiduModel;
private YoudaoModel mYoudaoModel;
@Inject
public TranslateService(BaiduModel baiduModel, YoudaoModel youdaoModel) {
mBaiduModel = baiduModel;
mYoudaoModel = youdaoModel;
}
@Override
public IBaiduModel getBaiduModel() {
return mBaiduModel;
}
@Override
public IYoudaoModel getYouDaoModel() {
return mYoudaoModel;
}
}
package com.yige.translate.mvp.model;
import com.yige.translate.mvp.model.bean.TransResult;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
/**
* Created by gxl on 2017/11/28.
*/
public interface YoudaoAPI {
@GET("?")
Observable<ResponseBody> translate(@QueryMap Map<String, String> map);
}
package com.yige.translate.mvp.model;
import com.yige.translate.mvp.model.baidu.MD5;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
/**
* Created by gxl on 2017/11/28.
*/
public class YoudaoModel implements IYoudaoModel {
private YoudaoAPI mYoudaoAPI;
@Inject
public YoudaoModel(YoudaoAPI youdaoAPI) {
mYoudaoAPI = youdaoAPI;
}
@Override
public Observable<ResponseBody> translate1(String query, String from, String to) {
return mYoudaoAPI.translate(getParams(query,from,to));
}
private Map<String,String> getParams(String query, String from, String to){
String appKey ="2bbece5300a58c9b";
String salt = String.valueOf(System.currentTimeMillis());
String sign = md5(appKey + query + salt+ "7k3GVXvHxpIEldmJwDuxzIftXcVyQ290");
Map params = new HashMap();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("sign", sign);
params.put("salt", salt);
params.put("appKey", appKey);
return params;
}
/**
* 生成32位MD5摘要
* @param string
* @return
*/
public static String md5(String string) {
if(string == null){
return null;
}
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
try{
byte[] btInput = string.getBytes("utf-8");
/** 获得MD5摘要算法的 MessageDigest 对象 */
MessageDigest mdInst = MessageDigest.getInstance("MD5");
/** 使用指定的字节更新摘要 */
mdInst.update(btInput);
/** 获得密文 */
byte[] md = mdInst.digest();
/** 把密文转换成十六进制的字符串形式 */
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}catch(NoSuchAlgorithmException | UnsupportedEncodingException e){
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.yige.translate.mvp.model.baidu;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
class HttpGet {
protected static final int SOCKET_TIMEOUT = 10000; // 10S
protected static final String GET = "GET";
public static String get(String host, Map<String, String> params) {
try {
// 设置SSLContext
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
String sendUrl = getUrlWithQueryString(host, params);
// System.out.println("URL:" + sendUrl);
URL uri = new URL(sendUrl); // 创建URL对象
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
}
conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
conn.setRequestMethod(GET);
int statusCode = conn.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
System.out.println("Http错误码:" + statusCode);
}
// 读取服务器的数据
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
builder.append(line);
}
String text = builder.toString();
close(br); // 关闭数据流
close(is); // 关闭数据流
conn.disconnect(); // 断开连接
return text;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static String getUrlWithQueryString(String url, Map<String, String> params) {
if (params == null) {
return url;
}
StringBuilder builder = new StringBuilder(url);
if (url.contains("?")) {
builder.append("&");
} else {
builder.append("?");
}
int i = 0;
for (String key : params.keySet()) {
String value = params.get(key);
if (value == null) { // 过滤空的key
continue;
}
if (i != 0) {
builder.append('&');
}
builder.append(key);
builder.append('=');
builder.append(encode(value));
i++;
}
return builder.toString();
}
protected static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 对输入的字符串进行URL编码, 即转换为%20这种形式
*
* @param input 原文
* @return URL编码. 如果编码失败, 则返回原文
*/
public static String encode(String input) {
if (input == null) {
return "";
}
try {
return URLEncoder.encode(input, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return input;
}
private static TrustManager myX509TrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
}
package com.yige.translate.mvp.model.baidu;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5编码相关的类
*
* @author wangjingtao
*
*/
public class MD5 {
// 首先初始化一个字符数组,用来存放每个16进制字符
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
/**
* 获得一个字符串的MD5值
*
* @param input 输入的字符串
* @return 输入字符串的MD5值
*
*/
public static String md5(String input) {
if (input == null)
return null;
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes("utf-8");
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
} catch (Exception e) {
return null;
}
}
/**
* 获取文件的MD5值
*
* @param file
* @return
*/
public static String md5(File file) {
try {
if (!file.isFile()) {
System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");
return null;
}
FileInputStream in = new FileInputStream(file);
String result = md5(in);
in.close();
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String md5(InputStream in) {
try {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
messagedigest.update(buffer, 0, read);
}
in.close();
String result = byteArrayToHex(messagedigest.digest());
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String byteArrayToHex(byte[] byteArray) {
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
char[] resultCharArray = new char[byteArray.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}
package com.yige.translate.mvp.model.baidu;
import java.util.HashMap;
import java.util.Map;
public class TransApi {
private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
private String appid;
private String securityKey;
public TransApi(){
this("20171126000099472","adIVJdw755SB83oq0Is0");
}
public TransApi(String appid, String securityKey) {
this.appid = appid;
this.securityKey = securityKey;
}
public String getTransResult(String query, String from, String to) {
Map<String, String> params = buildParams(query, from, to);
return HttpGet.get(TRANS_API_HOST, params);
}
public Map<String, String> buildParams(String query, String from, String to) {
Map<String, String> params = new HashMap<String, String>();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("appid", appid);
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
params.put("salt", salt);
// 签名
String src = appid + query + salt + securityKey; // 加密前的原文
params.put("sign", MD5.md5(src));
return params;
}
}
package com.yige.translate.mvp.model.bean;
/**
* Created by gxl on 2017/11/27.
*/
public class TransItem {
private String src;//原文
private String dst;//译文
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
}
package com.yige.translate.mvp.model.bean;
import java.util.List;
/**
* Created by gxl on 2017/11/27.
*/
public class TransResult {
private String from;//翻译源语言
private String to;//译文语言
private List<TransItem> trans_result;// MIXED LIST 翻译结果
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public List<TransItem> getTrans_result() {
return trans_result;
}
public void setTrans_result(List<TransItem> trans_result) {
this.trans_result = trans_result;
}
}
package com.yige.translate.mvp.presenter;
import com.yige.translate.mvp.view.IBaseView;
/**
* Created by gxl on 2017/11/26.
*/
public class BaiduContract {
public interface View extends IBaseView {
void setTranslateResult(String result);
}
public interface Presenter extends IBasePresenter{
void translate(String query, String from, String to);
void translate1(String query, String from, String to);
}
}
package com.yige.translate.mvp.presenter;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.yige.translate.mvp.model.IBaiduModel;
import com.yige.translate.mvp.model.ITranslateService;
import com.yige.translate.mvp.model.IYoudaoModel;
import com.yige.translate.mvp.model.TranslateService;
import com.yige.translate.mvp.model.bean.TransItem;
import com.yige.translate.mvp.model.bean.TransResult;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
/**
* Created by gxl on 2017/11/26.
*/
public class BaiduPresenter extends BasePresenter<IBaiduModel, BaiduContract.View>
implements
BaiduContract.Presenter {
public static final String TAG = BaiduPresenter.class.getSimpleName();
private ITranslateService mService;
@Inject
public BaiduPresenter(ITranslateService service, BaiduContract.View view) {
super(null, view);
this.mService = service;
// Log.v(TAG,model == null ? "model is null":"model is not null");
// Log.v(TAG,view == null ? "view is null":"view is not null");
}
@Override
public void translate(final String query, final String from, final String to) {
if (TextUtils.isEmpty(query)) {
Toast.makeText(mView.getContext(), "请输入查询的内容", Toast.LENGTH_LONG).show();
return;
}
Observable<TransResult> observable = mService.getBaiduModel().translate1(query, from, to);
observable.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Exception {
}
}).doFinally(new Action() {
@Override
public void run() throws Exception {
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<TransResult>() {
@Override
public void onSubscribe(Disposable d) {}
@Override
public void onNext(TransResult transResult) {
Log.v(TAG, "onNext start...");
Log.v(TAG, "from:" + transResult.getFrom());
Log.v(TAG, "to:" + transResult.getFrom());
StringBuilder stringBuilder = new StringBuilder();
for (TransItem transItem : transResult.getTrans_result()) {
stringBuilder
.append("src:" + transItem.getSrc() + "; dst:" + transItem.getDst() + "\n");
Log.v(TAG, "src:" + transItem.getSrc() + "; dst:" + transItem.getDst());
}
mView.setTranslateResult(stringBuilder.toString());
}
@Override
public void onError(Throwable e) {
Log.v(TAG, "onError start...");
Log.v(TAG, e.toString());
}
@Override
public void onComplete() {
Log.v(TAG, "onComplete start...");
}
});
}
@Override
public void translate1(String query, String from, String to) {
if (TextUtils.isEmpty(query)) {
Toast.makeText(mView.getContext(), "请输入查询的内容", Toast.LENGTH_LONG).show();
return;
}
Observable<ResponseBody> observable = mService.getYouDaoModel().translate1(query, from, to);
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {}
@Override
public void onNext(ResponseBody transResult) {
Log.v(TAG, "onNext start...");
mView.setTranslateResult(transResult.source().toString());
}
@Override
public void onError(Throwable e) {
Log.v(TAG, "onError start...");
Log.v(TAG, e.toString());
}
@Override
public void onComplete() {
Log.v(TAG, "onComplete start...");
}
});
}
@Override
public void start() {
}
@Override
public void destroy() {
}
}
package com.yige.translate.mvp.presenter;
import com.yige.translate.mvp.view.IBaseView;
import com.yige.translate.mvp.model.IBaseModel;
/**
* Created by gxl on 2017/11/27.
*/
public abstract class BasePresenter<M extends IBaseModel,V extends IBaseView> implements IBasePresenter {
public M mModel;
public V mView;
public BasePresenter(M model, V view) {
mModel = model;
mView = view;
}
}
package com.yige.translate.mvp.presenter;
/**
* Created by gxl on 2017/11/27.
*/
public interface IBasePresenter{
void start();
void destroy();
}
package com.yige.translate.mvp.view;
import android.content.Context;
/**
* Created by gxl on 2017/11/27.
*/
public interface IBaseView {
Context getContext();
void showLoading();
void hideLoading();
void showToast(String value);
}
package com.yige.translate.ui.activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import com.yige.translate.mvp.presenter.BasePresenter;
import com.yige.translate.mvp.view.IBaseView;
import javax.inject.Inject;
/**
* Created by gxl on 2017/11/27.
*/
public class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IBaseView {
@Inject
protected P mPresenter;
@Override
public Context getContext() {
return this;
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showToast(String value) {
}
}
package com.yige.translate.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.yige.translate.MyApplication;
import com.yige.translate.R;
import com.yige.translate.injection.component.DaggerAppComponent;
import com.yige.translate.injection.component.DaggerMainComponent;
import com.yige.translate.injection.module.MainModule;
import com.yige.translate.mvp.model.BaiduModel;
import com.yige.translate.mvp.presenter.BaiduPresenter;
import com.yige.translate.mvp.presenter.BaiduContract;
public class MainActivity extends BaseActivity<BaiduPresenter> implements BaiduContract.View {
public static final String TAG = MainActivity.class.getSimpleName();
private EditText mEditText;
private Button mBtnTranslateBaidu;
private Button mBtnTranslateYoudao;
private TextView mTxtResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.txt_query);
mBtnTranslateBaidu = findViewById(R.id.btn_translate_baidu);
mBtnTranslateYoudao = findViewById(R.id.btn_translate_youdao);
mTxtResult = findViewById(R.id.txt_result);
mBtnTranslateBaidu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPresenter.translate(mEditText.getText().toString(), "en", "zh");
}
});
mBtnTranslateYoudao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPresenter.translate1(mEditText.getText().toString(), "en", "zh");
}
});
DaggerMainComponent.builder().appComponent(MyApplication.getAppComponent())
.mainModule(new MainModule(this)).build().inject(this);
// BaiduModel baiduModel = DaggerMainComponent.builder().mainModule(new
// MainModule(this)).build().getBaiduModel();
// if(baiduModel == null){
// Log.v(TAG,"baidumodel is null");
// }else{
// Log.v(TAG,"baidumodel is not null");
// }
}
@Override
public void setTranslateResult(String result) {
mTxtResult.setText(result);
}
}
package com.yige.translate.ui.activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.yige.translate.R;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0"/>
<item
android:color="#00000000"
android:offset="1.0"/>
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1"/>
</vector>
<?xml version="1.0" encoding="utf-8"?>
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z"/>
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8"/>
</vector>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context="com.yige.translate.MainActivity">
<EditText
android:id="@+id/txt_query"
android:layout_width="match_parent"
android:layout_height="100dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" tools:ignore="MissingConstraints"/>
<TextView
android:id="@+id/txt_result"
android:layout_width="match_parent"
android:layout_height="471dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/txt_query"
tools:layout_editor_absoluteX="0dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
> <Button
android:id="@+id/btn_translate_baidu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="百度翻译"
tools:layout_editor_absoluteX="295dp"
tools:layout_editor_absoluteY="51dp"/>
<Button
android:id="@+id/btn_translate_youdao"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="有道翻译"
tools:layout_editor_absoluteX="182dp"
tools:layout_editor_absoluteY="51dp"/></LinearLayout>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
tools:context="com.yige.translate.ui.activity.SecondActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_second"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.yige.translate.ui.activity.SecondActivity"
tools:showIn="@layout/activity_second">
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="150dp"
android:layout_height="200dp"
android:src="@mipmap/abc"
android:scaleType="fitStart"
/>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
<resources>
<dimen name="fab_margin">16dp</dimen>
</resources>
<resources>
<string name="app_name">yigetraslate</string>
<string name="title_activity_second">SecondActivity</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
package com.yige.translate;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Mon Nov 27 17:02:30 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
include ':app'
yicheng @ d8868009
Subproject commit d88680097ce64cf657a1c859d8db7cd0b53b3378
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册