我不知道为什么您可能希望在没有滚动条的情况下拥有多行,但如果这是您需要的,我认为这可能是一个可能的解决方案。
显然,您需要在布局上完成一些逻辑,因为我想不出一个视图可以在不进行一些调整的情况下为您提供此服务。
所以,我在想一个带有 5 个 TextViews 的 RelativeLayout(textViews 的数量取决于你想显示多少行)。
因此,每个 textView 都将包含您的一行,因此当用户添加新行时,您必须按照这些行做一些事情:
if( linesInView == 5 )
shiftText();
addText();
所以这shiftText()
将负责通过一个循环并将一个 textView 的文本设置为另一个(移动它们),以便为新文本腾出空间。
然后addText()
只需将用户创建的新文本添加到由于shiftText()
.
总而言之,您可以遵循这些准则。请记住,我刚刚写下了这段代码,我目前没有办法检查它的正确性。另外,这是第一次尝试,还有改进的余地:
private static int MAX_NUM_LINES = 5;
private int linesShown = 0;
private ArrayList<TextView> views = new ArrayList<>();
private EditText userInput;
public void onCreate(...){
....
views.add((TextView)findViewById(R.id.firstline);
views.add((TextView)findViewById(R.id.secondline);
views.add((TextView)findViewById(R.id.thirdline);
views.add((TextView)findViewById(R.id.fourthline);
views.add((TextView)findViewById(R.id.fifthline);
this.userInput = (EditText) findViewById(R.id.input);
//I suggest these in order to avoid calling "findViewById()" everytime the user
// adds a new sentences, which I gather will happen often
}
public void someEventCalledWhenUserAddsNewLine(View view){
if(this.linesShown>=MAX_NUM_LINES)
shiftText();
addNewLine();
}
private void shiftText(){
//Shift your text by looping through your this.views
for(pos=0; pos<this.views.size()-1; ++pos){
String nextLine = this.views.get(pos+1).getText();
this.views.get(pos).setText(nextLine);
}
//You need to set the condition to this.views.size()-1 because
//when you reach position 4 (your last TextView) you have to sop
// since there is not text to shift to that one
this.views.get(this.views.size()-1).setText(null);
//Make sure you set the text of the last TextView to null so that
// addLine() will be able to find the first available TextView
}
private void addNewLine(){
//Add text from this.userInput to the first available TextView in this.views
int pos;
for(pos=0; pos<this.views.size(); ++pos){
if(this.views.get(pos).getText()==null){
//We have found the first available TextView
break;
}
}
this.views.get(pos).setText(this.userInput.getText());
//Pos holds the position of the first available TextView, now we have
// added the new line
this.linesShown++;
}
蝙蝠改进的首要任务是跟踪第一个可用 TextView 的索引,这样您就不必在addLine()
寻找它时弄乱循环。