简体   繁体   中英

Making TextView Scrollable in Android programmatically

I want to make textView programmatically and make them scrollable. I am calling this method again and again to get textView and adding it to the linearLayout .

TextView textView = addTextView(contents.paragraphs.get(i),false);
linearLayout.addView(textView);

But, it is not scrollable at all. The method is:

private TextView addTextView(String text,boolean type) {
        TextView valueTV = new TextView(this);
        valueTV.setText(text);
        valueTV.setTextColor(getResources().getColor(R.color.colorTextPrimary));
        valueTV.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        valueTV.setMaxLines(1000);
        valueTV.setVerticalScrollBarEnabled(true);
        valueTV.setMovementMethod(new ScrollingMovementMethod());

        return valueTV;
}

Change to:

valueTV.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));

If you use WRAP_CONTENT the TextView will increase height 'indefinitely'.

You can wrap the TextView into a ScrollView

 ViewGroup linearLayout = findViewById(R.id.linear_layout);
 TextView textView = addTextView(contents.paragraphs.get(i), false);
 ScrollView scroller = new ScrollView(getApplicationContext());
 scroller.addView(textView);
 linearLayout.addView(scroller);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM