1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SelectionContainerのweightが上手く動作しない時の対処法

Last updated at Posted at 2025-02-17

初めに

この記事では対処法は記載していますが、根本的な原因については言及していません。
ご存知の方がいらっしゃいましたら、教えていただけると助かります。

JetPack ComposeでSelectionContainerを使う時に、
weightの動作がBoxなどと違う場合があります。(weightが適切に分配されないなど)

この記事では、そのような問題が発生した際の対処法を記載しています。

関連する問題

この問題がGoogle Issue Trackerでも挙げられていました。
このIssueの結論としては、「回避策が存在するため、現状のレイアウトの崩壊を防ぐために、緊急修正(hotfix)する予定はなし。」というような感じでした。

対処法

Google Issue Trackerの情報によると、SelectionContainerからModifier.weightを外し、
Box(modifier = Modifier.weight(1f), propagateMinConstraints = true)
囲うと適切に動作するようになるそうです。

// 問題が発生する可能性のあるコンポーネント
@Composable
private fun Sample(
    text: String,
    modifier: Modifier = Modifier,
) {
    Scaffold(
    ) { innerPadding ->
        Box(Modifier.padding(innerPadding)) {
            Column(
                modifier = modifier,
            ) {
                SelectionContainer(modifier = Modifier.weight(1f)) {
                    Text(text = text)
                }
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .background(color = Color.Red),
                )
            }
        }
    }
}
// weightが適切に動作するように修正したコンポーネント
@Composable
private fun Sample(
    text: String,
    modifier: Modifier = Modifier,
) {
    Scaffold(
    ) { innerPadding ->
        Box(Modifier.padding(innerPadding)) {
            Column(
                modifier = modifier,
            ) {
                // Box を新たに追加
                Box(modifier = Modifier.weight(1f), propagateMinConstraints = true) {
                    SelectionContainer { // Modifier.weightを削除
                        Text(text = text)
                    }
                }
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .background(color = Color.Red),
                )
            }
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?