
在你的 activity 或 fragment 的 xml 布局文件中,添加 flowlayout。
<com.nex3z.flowlayout.FlowLayout
android:id="@+id/flow_id"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.nex3z.flowlayout.FlowLayout>在 Activity 的 onCreate() 方法中,获取 FlowLayout 的实例,然后将句子分割成单词,并为每个单词创建一个 TextView,添加到 FlowLayout 中。
// 在 onCreate() 方法中
FlowLayout flowLayout = findViewById(R.id.flow_id);
String sentence = "I do not like anyone in this world of idiots";
String[] words = sentence.split(" ");
TextView wordText;
int keywordIndex = 3; // 假设 "like" 是要填写的关键词,索引为3
for (int i = 0; i < words.length; i++) {
String word = words[i];
// 如果是关键词,则创建 EditText,否则创建 TextView
if (i == keywordIndex) {
wordText = new EditText(this);
wordText.setHint("____");
wordText.setWidth(100); //设置宽度,单位px
} else {
wordText = new TextView(this);
wordText.setText(word);
}
wordText.setTextColor(getResources().getColor(R.color.black)); // 设置颜色
wordText.setBackgroundColor(getResources().getColor(android.R.color.white)); // 设置背景色
FlowLayout.LayoutParams params = new FlowLayout.LayoutParams(
FlowLayout.LayoutParams.WRAP_CONTENT,
FlowLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5,5,5,5); //设置边距,单位dp
wordText.setLayoutParams(params);
flowLayout.addView(wordText);
}代码解释:
除了 FlowLayout,还可以使用 RecyclerView 配合 GridLayoutManager 或 StaggeredGridLayoutManager 来实现类似的效果。但是,使用 RecyclerView 需要创建 RecyclerView.Adapter,相对来说更复杂一些。RecyclerView 更适合用于显示垂直排列的句子集合,而不是单个句子的单词排列。
通过本文的介绍,你应该能够掌握如何使用 FlowLayout 在 Android 中实现 TextView 文本的动态分割和布局,从而解决填字游戏等场景下的 UI 显示问题。
以上就是Android TextView 多行文本分割与动态布局:打造填字游戏的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号