2024年2月27日火曜日

Android Studio (IntelliJ IDEA) の Replace の正規表現モードを使う

例えば assertThat(answer).isEqualTo(2) assertEquals(2, answer) に置き換えたい場合、Replace の正規表現モードを使うことで簡単に変換できる。

Cmd + Shift + R で Replace in Files window を開き、
(そのファイルだけ置き換えたいときは Cmd + R)
変換元を入力するフィールドの右端の 「.*」 部分をオンにする。

変換元に assertThat\((.*)\)\.isEqualTo\((.*)\) 変換先に assertEquals\($2, $1\) と入れて、Replace All ボタンを押すと全部置き換わる。便利!




2023年12月25日月曜日

InlineTextContent を使って Composable のテキスト中にアイコンを表示する

val id = "inlineContent" val inlineContent = mapOf( Pair( id, InlineTextContent( Placeholder( width = 1.em, height = 1.em, placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline ) ) { Icon(imageVector = Icons.Default.OpenInNew, contentDescription = null) } ) ) Text( text = buildAnnotatedString { append("open here") appendInlineContent(id, "[open in new]") }, inlineContent = inlineContent, fontSize = 24.sp, ) PlaceholderVerticalAlign で上下の位置を指定できる。中央揃えにするなら PlaceholderVerticalAlign.TextCenter がよさげ。

2023年7月15日土曜日

ActivityResultContracts.CreateDocument に指定する mimeType には * を使ってはいけない

mimeType に "text/*"、ファイル名に "sample.csv" を指定した場合、ファイル名が重複したときの "(1)" が拡張子の後につけられてしまう。 @Composable fun CreateDocumentSample() { val createDocumentLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/*")) { if (it != null) { ... } } Button( onClick = { createDocumentLauncher.launch("sample.csv") } ) { Text("Click") } }


mimeType を "text/csv" にし、ファイル名を "sample.csv" や "sample" にした場合、ファイル名が重複したときの "(1)" が拡張子の前になる。 @Composable fun CreateDocumentSample() { val createDocumentLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/csv")) { if (it != null) { ... } } Button( onClick = { createDocumentLauncher.launch("sample.csv") } ) { Text("Click") } }
@Composable fun CreateDocumentSample() { val createDocumentLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/csv")) { if (it != null) { ... } } Button( onClick = { createDocumentLauncher.launch("sample") } ) { Text("Click") } }


名前についている拡張子が mimeType と異なる場合その部分は拡張子とは認識されず、mimeType に基づいた拡張子がつきます。

以下では mimeType が "text/plain" でファイル名が "sample.csv" なので ".csv" は拡張子とは認識されず、実際のファイル名は "sample.csv.txt" になります。 @Composable fun CreateDocumentSample() { val createDocumentLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { if (it != null) { ... } } Button( onClick = { createDocumentLauncher.launch("sample.csv") } ) { Text("Click") } }