java - 如何在ScrollView的底部添加字符串

标签 java android string button scrollview

我想知道如何在每次按下按钮时在 ScrollView 底部添加新字符串。

比如开头有sentence1,按下按钮,则sentence2sentence1下,按下按钮,sentence3 位于 sentence2

我知道如何制作 ScrollView ,并且我有一个要显示的字符串数组:

final int[] sentences = new int[]{
        R.String.sentence1, 
        R.String.sentence1, 
        R.String.sentence2, 
        R.String.sentence3, 
        R.String.sentence4
};

而且我知道如何在按下按钮时使它们依次出现(类似于替换前一个,就像 TextSwitch 但没有动画):

if(nextSentenceId < sentences.length) {
   officeOBSDialog.setText(sentences[nextSentenceId]);
   ++nextSentenceId;
}

你知道我该如何做到这一点或者我可以使用什么吗?我突然想到我可以像布局充气机一样使用,但我不知道如何将其付诸实践以及将其放在哪里。提前致谢

最佳答案

我建议您使用ListViewRecyclerViewhttps://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView

但是,如果您一直想使用 ScrollView 因为您的屏幕 UI 很简单。您可以简单地用 ScrollView 包装垂直方向的 LinearLayout。

activity.xml

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:id="@+id/lnContainer"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- your button declaration -->

    </LinearLayout>
</ScrollView>

在您的 Activity java 文件中,通过以下方式以编程方式添加新行:

private int position=0;
final int[] sentences = new int[]{
    R.String.sentence1, 
    R.String.sentence1, 
    R.String.sentence2, 
    R.String.sentence3, 
    R.String.sentence4
};

//inside onCreate() method
yourButton.setOnClickListener(new View.OnClickListener(){
     public void onClick(View view){
         TextView textView = new TextView(YourActivityClass.this);
         textView.setText(sentences[position++]);
         ((LinearLayout)findViewById(R.id.lnContainer)).addView(textView);
     }
});

关于java - 如何在ScrollView的底部添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292792/

相关文章:

java - 创建名称为 'Individual_Controller' : Injection of autowired dependencies failed; 的 bean 时出错

java - asyncTask 中的 findViewById()

php - 检查字符串是否只包含php中的数字

c - 使用 4-7 个字母在文本文件中查找整个单词

java - 使用 jackrabbit 存储图像等静态内容并使用 servlet 读取它们并将其作为图像流传输给用户对性能有何影响?

java - Spring @RequestMapping,404错误

java - 线程 "main"java.io.FileNotFoundException : when running maven project using java -cp command 中出现异常

android - 如何在这些复选框上使用 ScrollView

Android gridview 适配器为零位置调用多个 getview()

string - 要删除的最小子串的长度