質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

解決済

1回答

989閲覧

Android Studioにて、KotlinでのLogin_activityについて

Tesra3

総合スコア10

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

0クリップ

投稿2019/03/22 15:36

編集2019/03/22 15:41

前提

C言語は勉強済み
Kotlinを勉強し始めたばかりで、長澤太郎 著「Kotlinスタートブック」を見ながら勉強しています。
ある団体でアプリを作成しようとしているのですが、そのログイン画面を作ろうとしています。

伺いたいこと

Android StudioのLogin_activityのファイル「LoginActivity.kt」のコードを解読しているのですが、本には記載されていないコード(11行目のsuperなど)があり、どのような仕組みになっているのか分かりません。一部分であったり、簡単にでも大丈夫ですので、何が書かれているのか教えていただきたいです。コードが凄く長文ですいません。

該当のソースコード

Kotlin

1 2class LoginActivity : AppCompatActivity(), LoaderCallbacks<Cursor> { 3 4 private var mAuthTask: UserLoginTask? = null 5 6 override fun onCreate(savedInstanceState: Bundle?) { 7 super.onCreate(savedInstanceState) 8 setContentView(R.layout.activity_login) 9 // Set up the login form. 10 populateAutoComplete() 11 password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ -> 12 if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) { 13 attemptLogin() 14 return@OnEditorActionListener true 15 } 16 false 17 }) 18 19 email_sign_in_button.setOnClickListener { attemptLogin() } 20 } 21 22 private fun populateAutoComplete() { 23 if (!mayRequestContacts()) { 24 return 25 } 26 27 loaderManager.initLoader(0, null, this) 28 } 29 30 private fun mayRequestContacts(): Boolean { 31 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { 32 return true 33 } 34 if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { 35 return true 36 } 37 if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { 38 Snackbar.make(email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) 39 .setAction(android.R.string.ok, 40 { requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) }) 41 } else { 42 requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) 43 } 44 return false 45 } 46 47 override fun onRequestPermissionsResult( 48 requestCode: Int, permissions: Array<String>, 49 grantResults: IntArray 50 ) { 51 if (requestCode == REQUEST_READ_CONTACTS) { 52 if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 53 populateAutoComplete() 54 } 55 } 56 } 57 58 private fun attemptLogin() { 59 if (mAuthTask != null) { 60 return 61 } 62 63 // Reset errors. 64 email.error = null 65 password.error = null 66 67 // Store values at the time of the login attempt. 68 val emailStr = email.text.toString() 69 val passwordStr = password.text.toString() 70 71 var cancel = false 72 var focusView: View? = null 73 74 // Check for a valid password, if the user entered one. 75 if (!TextUtils.isEmpty(passwordStr) && !isPasswordValid(passwordStr)) { 76 password.error = getString(R.string.error_invalid_password) 77 focusView = password 78 cancel = true 79 } 80 81 // Check for a valid email address. 82 if (TextUtils.isEmpty(emailStr)) { 83 email.error = getString(R.string.error_field_required) 84 focusView = email 85 cancel = true 86 } else if (!isEmailValid(emailStr)) { 87 email.error = getString(R.string.error_invalid_email) 88 focusView = email 89 cancel = true 90 } 91 92 if (cancel) { 93 // There was an error; don't attempt login and focus the first 94 // form field with an error. 95 focusView?.requestFocus() 96 } else { 97 // Show a progress spinner, and kick off a background task to 98 // perform the user login attempt. 99 showProgress(true) 100 mAuthTask = UserLoginTask(emailStr, passwordStr) 101 mAuthTask!!.execute(null as Void?) 102 } 103 } 104 105 private fun isEmailValid(email: String): Boolean { 106 //TODO: Replace this with your own logic 107 return email.contains("@") 108 } 109 110 private fun isPasswordValid(password: String): Boolean { 111 //TODO: Replace this with your own logic 112 return password.length > 4 113 } 114 115 @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) 116 private fun showProgress(show: Boolean) { 117 // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow 118 // for very easy animations. If available, use these APIs to fade-in 119 // the progress spinner. 120 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { 121 val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong() 122 123 login_form.visibility = if (show) View.GONE else View.VISIBLE 124 login_form.animate() 125 .setDuration(shortAnimTime) 126 .alpha((if (show) 0 else 1).toFloat()) 127 .setListener(object : AnimatorListenerAdapter() { 128 override fun onAnimationEnd(animation: Animator) { 129 login_form.visibility = if (show) View.GONE else View.VISIBLE 130 } 131 }) 132 133 login_progress.visibility = if (show) View.VISIBLE else View.GONE 134 login_progress.animate() 135 .setDuration(shortAnimTime) 136 .alpha((if (show) 1 else 0).toFloat()) 137 .setListener(object : AnimatorListenerAdapter() { 138 override fun onAnimationEnd(animation: Animator) { 139 login_progress.visibility = if (show) View.VISIBLE else View.GONE 140 } 141 }) 142 } else { 143 // The ViewPropertyAnimator APIs are not available, so simply show 144 // and hide the relevant UI components. 145 login_progress.visibility = if (show) View.VISIBLE else View.GONE 146 login_form.visibility = if (show) View.GONE else View.VISIBLE 147 } 148 } 149 150 override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> { 151 return CursorLoader( 152 this, 153 // Retrieve data rows for the device user's 'profile' contact. 154 Uri.withAppendedPath( 155 ContactsContract.Profile.CONTENT_URI, 156 ContactsContract.Contacts.Data.CONTENT_DIRECTORY 157 ), ProfileQuery.PROJECTION, 158 159 // Select only email addresses. 160 ContactsContract.Contacts.Data.MIMETYPE + " = ?", arrayOf( 161 ContactsContract.CommonDataKinds.Email 162 .CONTENT_ITEM_TYPE 163 ), 164 165 // Show primary email addresses first. Note that there won't be 166 // a primary email address if the user hasn't specified one. 167 ContactsContract.Contacts.Data.IS_PRIMARY + " DESC" 168 ) 169 } 170 171 override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor) { 172 val emails = ArrayList<String>() 173 cursor.moveToFirst() 174 while (!cursor.isAfterLast) { 175 emails.add(cursor.getString(ProfileQuery.ADDRESS)) 176 cursor.moveToNext() 177 } 178 179 addEmailsToAutoComplete(emails) 180 } 181 182 override fun onLoaderReset(cursorLoader: Loader<Cursor>) { 183 184 } 185 186 private fun addEmailsToAutoComplete(emailAddressCollection: List<String>) { 187 //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. 188 val adapter = ArrayAdapter( 189 this@LoginActivity, 190 android.R.layout.simple_dropdown_item_1line, emailAddressCollection 191 ) 192 193 email.setAdapter(adapter) 194 } 195 196 object ProfileQuery { 197 val PROJECTION = arrayOf( 198 ContactsContract.CommonDataKinds.Email.ADDRESS, 199 ContactsContract.CommonDataKinds.Email.IS_PRIMARY 200 ) 201 val ADDRESS = 0 202 val IS_PRIMARY = 1 203 } 204 205 inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : 206 AsyncTask<Void, Void, Boolean>() { 207 208 override fun doInBackground(vararg params: Void): Boolean? { 209 // TODO: attempt authentication against a network service. 210 211 try { 212 // Simulate network access. 213 Thread.sleep(2000) 214 } catch (e: InterruptedException) { 215 return false 216 } 217 218 return DUMMY_CREDENTIALS 219 .map { it.split(":") } 220 .firstOrNull { it[0] == mEmail } 221 ?.let { 222 // Account exists, return true if the password matches. 223 it[1] == mPassword 224 } 225 ?: true 226 } 227 228 override fun onPostExecute(success: Boolean?) { 229 mAuthTask = null 230 showProgress(false) 231 232 if (success!!) { 233 finish() 234 } else { 235 password.error = getString(R.string.error_incorrect_password) 236 password.requestFocus() 237 } 238 } 239 240 override fun onCancelled() { 241 mAuthTask = null 242 showProgress(false) 243 } 244 } 245 246 companion object { 247 248 private val REQUEST_READ_CONTACTS = 0 249 250 private val DUMMY_CREDENTIALS = arrayOf("foo@example.com:hello", "bar@example.com:world") 251 } 252}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2019/03/22 19:35

ご希望の回答ではないと思いますので, こちらで失礼致します. まず super をご理解頂いた方が宜しいかと思います. また, 実際に動くコードですしコメントも入っていますので, 動かしながら kotlin の学習を進められては如何でしょうか.
Tesra3

2019/03/23 01:43

やはりそのほうがいいですかね…。 ありがとうございます。m(_ _)m
guest

回答1

0

自己解決

やはり独学で細かく理解するのは厳しいので、とりあえず書いてあるものをコピペして応用を効かせていくようにしていきます。

投稿2019/03/23 15:38

Tesra3

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問