Skip to content

Commit a170248

Browse files
committed
検索処理を記述する
1 parent 402f651 commit a170248

File tree

1 file changed

+55
-4
lines changed

1 file changed

+55
-4
lines changed

app/src/main/java/com/example/kotlin_qiita_client/MainActivity.kt

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,19 @@ package com.example.kotlin_qiita_client
33
import android.content.Context
44
import androidx.appcompat.app.AppCompatActivity
55
import android.os.Bundle
6+
import android.text.TextUtils
7+
import android.util.Log
8+
import android.view.KeyEvent
69
import android.view.View
710
import android.view.ViewGroup
8-
import android.widget.ArrayAdapter
9-
import android.widget.ImageView
10-
import android.widget.ListView
11-
import android.widget.TextView
11+
import android.view.inputmethod.InputMethodManager
12+
import android.widget.*
1213
import com.squareup.picasso.Picasso
14+
import retrofit2.Call
15+
import retrofit2.Callback
16+
import retrofit2.Response
17+
import java.io.UnsupportedEncodingException
18+
import java.net.URLEncoder
1319

1420
class MainActivity : AppCompatActivity() {
1521

@@ -23,6 +29,9 @@ class MainActivity : AppCompatActivity() {
2329

2430
val listView = findViewById<ListView>(R.id.list_view) as ListView
2531
listView.adapter = mAdapter
32+
33+
val editText = findViewById<EditText>(R.id.edit_text) as EditText
34+
editText.setOnKeyListener(OnKeyListener())
2635
}
2736

2837
private inner class ListAdapter(context: Context, resource: Int) :
@@ -51,4 +60,46 @@ class MainActivity : AppCompatActivity() {
5160
return convertView
5261
}
5362
}
63+
64+
private inner class OnKeyListener : View.OnKeyListener {
65+
66+
override fun onKey(view: View, keyCode: Int, keyEvent: KeyEvent): Boolean {
67+
if (keyEvent.action != KeyEvent.ACTION_UP || keyCode != KeyEvent.KEYCODE_ENTER) {
68+
return false
69+
}
70+
71+
val editText = view as EditText
72+
// キーボードを閉じる
73+
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
74+
imm.hideSoftInputFromWindow(editText.windowToken, 0)
75+
76+
var text = editText.text.toString()
77+
try {
78+
// url encode 例. スピッツ > %83X%83s%83b%83c
79+
text = URLEncoder.encode(text, "UTF-8")
80+
} catch (e: UnsupportedEncodingException) {
81+
Log.e("", e.toString(), e)
82+
return true
83+
}
84+
85+
if (!TextUtils.isEmpty(text)) {
86+
val request = QiitaClient.create().items(text)
87+
Log.d("", request.request().url().toString())
88+
val item = object : Callback<List<Item>> {
89+
override fun onResponse(
90+
call: Call<List<Item>>?,
91+
response: Response<List<Item>>?
92+
) {
93+
mAdapter.clear()
94+
response?.body()?.forEach { mAdapter.add(it) }
95+
}
96+
97+
override fun onFailure(call: Call<List<Item>>?, t: Throwable?) {
98+
}
99+
}
100+
request.enqueue(item)
101+
}
102+
return true
103+
}
104+
}
54105
}

0 commit comments

Comments
 (0)