
2. 在 XML 布局文件中添加 FlowLayout
在你的 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>3. 在 Activity 中动态创建 TextView
在 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);
}代码解释:
- sentence.split(" "): 将句子按照空格分割成单词数组。
- keywordIndex: 指定需要用户填写的关键词的索引。
- EditText: 用于用户输入关键词,并设置了提示文字 "____"。
- wordText.setTextColor() 和 wordText.setBackgroundColor(): 设置TextView的颜色和背景色。
- flowLayout.addView(wordText): 将创建的TextView添加到FlowLayout中。
- FlowLayout.LayoutParams: 设置TextView的边距,使其在FlowLayout中看起来更美观。
4. 替代方案:RecyclerView
除了 FlowLayout,还可以使用 RecyclerView 配合 GridLayoutManager 或 StaggeredGridLayoutManager 来实现类似的效果。但是,使用 RecyclerView 需要创建 RecyclerView.Adapter,相对来说更复杂一些。RecyclerView 更适合用于显示垂直排列的句子集合,而不是单个句子的单词排列。
注意事项与总结
- 使用 FlowLayout 可以避免 getLineCount() 方法的局限性,实现更可靠的文本分割和动态布局。
- 在创建 TextView 时,可以根据需要设置不同的属性,例如字体大小、颜色、背景色等。
- FlowLayout 能够自动处理换行,无需手动计算换行位置。
- 可以根据实际需求选择 FlowLayout 或 RecyclerView,FlowLayout 更适合简单的单词排列,RecyclerView 更适合复杂的列表展示。
- 注意设置FlowLayout.LayoutParams,调整TextView之间的间距,使布局更美观。
通过本文的介绍,你应该能够掌握如何使用 FlowLayout 在 Android 中实现 TextView 文本的动态分割和布局,从而解决填字游戏等场景下的 UI 显示问题。











