Androidは覚えることが多く情報をまとめて記すのが難しいので各特長ごとにまとめた記事を書くことにしました。ここではLayout(View)に関する情報で覚えておきたいことをメモ書きのように書き残しておきます。まだ勉強中なので随時更新していきます。
テキストにリンクを設置するとき
android: autoLink="all"
// webでurl, emailでメール,phoneで電話番号が指定できる。 email | phoneと区切り指定もできる
でTextViewに含まれるメールアドレスやURL、電話番号に対するリンクを自動的に生成する。
android:lineSpacingMultiplier : 行間の指定ができる。
android:ellipsesize : テキストの切り捨ての際"..."を付与することができる。
例)android:ellipsesize=start or middle or end
app:srcCompat="@drawable/ベース名(画像のファイル名)" : 表示する画像を選択
android:contentDescription="文" : 代替テキストの生成
android:scaleY : 垂直方向の倍率
android:scaleX : 水平方向の倍率
android:alpha :透過度(0.0~1.0)
画像でできたボタン作れる。
ボタンに対する動作によってボタンの画像に変化をつけたいときは複数の画像をxmlで管理しselectorとitemで動作ごとに表示する画像を選択すると楽。注意すべきことがひとつあり、このselectorは記述されているものを上から順に条件にマッチしているかどうか調べていきマッチした時点でそれを表示していくという仕組みになっている。つまり記述していく順番を間違えると思った画像が表示されないことがある(デフォルト画像は一番下にすべし)。amdroid:state_@@@="true"で状態を判定しているが何も記述していない場合それがデフォルト、つまり無条件で画像表示する仕組みになっている。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn3"
android:state_pressed="true"/>
<item android:drawable="@drawable/btn2"
android:state_hovered="true"/>
<item android:drawable="@drawable/btn1"/>
</selector>
EditTextは文字入力ウィジェット。
複数行のテキストエディターの指定
入力する内容を指定することができる(パスワードとか番号とか)
android:inputType="入力タイプ"
入力タイプの例) text(通常), textAutoCorrect(スペルチェック付き), textAutoComplete(自動補完), textEmailAddress, number, textPassword, phone, numberSigned
android:inputType="textMultiLine" android:lines="3"
入力ヒントの指定
android:hint="文章"
アプリ起動時にエディタにフォーカスを当てたいとき
<request />
android:checked : 初期状態でチェックを入れるかを設定できる。
val chk: CheckBox = findViewById(R.id.chk)
chk.setOnCheckedChangeListener { buttonView, isChecked ->
Toast.makeText(applicationContext, if(isChecked) "on" else "off", Toast.LENGTH_SHORT).show()
}
chk.setOnCheckedChangeListener{
_, isChecked -> run{Toast.makeText(applicationContext, if(isChecked) "on" else "off", Toast.LENGTH_SHORT).show()}
}
注意点 : 各RadioButtonにIDを振らないとチェックがうまく入らない
RadioButton Layoutの例)
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioButton
android:id="@+id/rda"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="a"/>
<RadioButton
android:id="@+id/rdb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="b"/>
<RadioButton
android:id="@+id/rdc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="c"/>
</RadioGroup>
ActivityでのRradioButton選択時のアクションの例)
val rgroup: RadioGroup = findViewById(R.id.rgroup)
rgroup.setOnCheckedChangeListener { group, checkedId ->
run{
val radio: RadioButton = group.findViewById(checkedId)
Toast.makeText(applicationContext, "${radio.text}が選択されました。", Toast.LENGTH_SHORT).show()
}
}
複数の選択肢から一つ選べる機能。ダイアログ表示とドロップダウンメニューの二つある。
Layout 例)
<Spinner
android:id="@+id/spnOs"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:entries="@array/spnOs_items" //配列の取得
android:prompt="@string/spnOs_prompt" //ダイアログ表示の時に使用
android:spinnerMode="dialog" //ダイアログ表示にできる。ない場合デフォルトでdropdownになる
/>
Stringファイル 例)
<string name="spnOs_prompt">OSを選択してくださ</string> //ダイアログ表示の時に使用
<string-array name="spnOs_items"> //配列保存
<item>Windows</item> //各要素
<item>macOs</item>
<item>Linux</item>
<item>Original Special</item>
</string-array>
Activity 例)
val sp:Spinner = findViewById(R.id.spnOs)
sp.setOnItemSelectedListener(
object :AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?, //配列を引き渡している
view: View?,
position: Int,
id: Long
) {
val sp: Spinner = parent as Spinner //キャスト
Toast.makeText(applicationContext, "選択項目 : ${sp.selectedItem}",Toast.LENGTH_SHORT).show()
}
}
)
動的にActivity から直接Spinnerを生成できる。
Activity例)//layoutファイルは省略します
fun createSpinner(){
var list: ArrayList<String> = arrayListOf()
val format: SimpleDateFormat = SimpleDateFormat("yyyy/MM/dd", Locale.JAPAN)
val cal: Calendar = Calendar.getInstance()
for(i in 1..11){
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+1)
list.add(format.format(cal.getTime()))
}
val adapter:ArrayAdapter<String> = ArrayAdapter(this.getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, list)
val spn: Spinner = findViewById(R.id.spnArch)
spn.setAdapter(adapter)
spn.setOnItemSelectedListener(
object :AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
val sp: Spinner = parent as Spinner
Toast.makeText(applicationContext, "選択項目 : ${sp.selectedItem}",Toast.LENGTH_SHORT).show()
}
}
)
}
Listを簡単に表示するためのView。
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/list_string" //配列を指定している。
/>
ListViewに対する操作の例 )
val data:ArrayList<String> = ArrayList()
data.add("胡椒")
data.add("ターメリック")
data.add("コリアンダー")
data.add("生姜")
data.add("ニンニク")
data.add("サフラン")
val adapter:ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, data)
val list: ListView = findViewById(R.id.list)
list.adapter = adapter
list.setOnItemLongClickListener { _, view, position, _->
if(position == adapter.count -1) {
return@setOnItemLongClickListener false
}
val msg:String? = (view as TextView ).text as String?
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
adapter.remove(msg)
true
}
val adapter:ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
val list: ListView = findViewById(R.id.list)
list.adapter = adapter
list.setOnItemLongClickListener { //これは長押し指定の場合。クリックで動作させたければsetOnItemLongClickListener
parent, view, position, id->
adapter.remove((view as TextView ).text as String?)
true //処理を完了させる。項目によってクリックイベントを作りたいならposition等で条件分岐をつくりfalseとすればよい
}
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice" //ラジオボタンの場合
android:choiceMode="multipleChoice" //チェックボタンの場合
/>
val data:ArrayList<String> = ArrayList() //リスト動的生成
data.add("胡椒")
data.add("ターメリック")
data.add("コリアンダー")
data.add("生姜")
data.add("ニンニク")
data.add("サフラン")
//ラジオボタンの場合
val adapter:ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, data)
//チェックボタンの場合
val adapter:ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, data)
val list: ListView = findViewById(R.id.list)
list.adapter = adapter
list.setOnItemLongClickListener { _, view, position, _->
if(position == adapter.count -1) {
return@setOnItemLongClickListener false
}
val msg:String? = (view as TextView ).text as String?
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
true
}
Switch
layout 例)
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true" //textOff, textOnのテキストを表示する
android:text="send?" //ラベル
android:textOff="no" //off時のテキスト
android:textOn="yes" ////on時のテキスト
android:checked="true" //初期の状態
/>
SeekBar : ある範囲の連続した数値の入力できる。スライダーで値が入力できる。
layout 例)
<SeekBar
android:id="@+id/seek"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="200" //最大値の設定
android:progress="100" //初期値の設定
/>
Activity 例)
val seek:SeekBar = findViewById(R.id.seek)
seek.setOnSeekBarChangeListener(
object: SeekBar.OnSeekBarChangeListener{
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean ) {
//seekBar : イベントの発生元, progress : 現在値, fromUser : ユーザーによる操作か否か
// Toast.makeText(applicationContext, "現在地 : ${progress}",Toast.LENGTH_SHORT).show()
////つまみを動かしている間の処理
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
//つまみタッチしたときの処理
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
Toast.makeText(applicationContext, "現在地 : ${seek.progress}",Toast.LENGTH_SHORT).show()
//つまみ離した時の処理
}
}
)
RatingBar
Layout 例)
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="6"
android:rating="4.7"
android:stepSize="0.1"/>
Activity 例)
val rate: RatingBar = findViewById(R.id.rating)
rate.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
Toast.makeText(applicationContext, "現在の評価は${rating}です。", Toast.LENGTH_SHORT).show()
}
[1]Android 状態によって色を変える | suka4's memo
[2] TECHNICAL MASTER はじめてのAndroidアプリ開発 第3版 Android Studio 3対応
著: 山田 祥寛