Skip to content

Instantly share code, notes, and snippets.

@engincancan
Last active March 12, 2019 08:46
Show Gist options
  • Save engincancan/f06fc97b7bf89930b1d9bd913a17599f to your computer and use it in GitHub Desktop.
Save engincancan/f06fc97b7bf89930b1d9bd913a17599f to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/inputToTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="48dp"
android:layout_marginBottom="16dp"
android:ems="10"
android:hint="Enter text"
android:inputType="text" />
<Button
android:id="@+id/translateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="32dp"
android:text="Translate" />
<TextView
android:id="@+id/translatedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="16sp" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--Activities below as usual-->
</manifest>
class MainActivity : AppCompatActivity() {
private var translate: Translate? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getTranslateService()
translateButton.setOnClickListener {
if (checkInternetConnection()) {
translate()
} else {
translatedText.text = getString(R.string.no_connection)
}
}
}
private fun getTranslateService() {
try {
resources.openRawResource(R.raw.credentials).use { `is` ->
val myCredentials = GoogleCredentials.fromStream(`is`)
val translateOptions = TranslateOptions.newBuilder().setCredentials(myCredentials).build()
translate = translateOptions.service
}
} catch (ioe: IOException) {
ioe.printStackTrace()
}
}
private fun translate() {
val translation = translate!!.translate(
inputToTranslate.text.toString(),
Translate.TranslateOption.targetLanguage("tr"),
Translate.TranslateOption.model("base")
)
//Translated text is set to the TextView:
translatedText.text = translation.translatedText
}
private fun checkInternetConnection(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
return activeNetwork?.isConnected == true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment