正如 Ferran 所说,initializeScrollBars() 已被删除。请参阅here 了解错误报告及其删除的理由。据我所知,没有其他严格的编程方式可以为视图指定 scollbars。所有路径都通过 XML。 :-(
我认为 Ferran 的回答是一个很好的方法:它有效、易于理解并且应该易于记录。但是,还有其他方法可以通过样式来以编程方式创建带有滚动条的 TextView。
适用于 API 21 及更高版本
定义一个名为“ViewWithScrollBars”的样式如下:
<style name="ViewWithScrollbars">
<item name="android:scrollbars">vertical</item>
</style>
我们现在可以使用 TextView 的四参数构造函数来应用样式。
TextView tv = new TextView(this, null, 0, R.style.ViewWithScrollbars);
此方法将创建一个带有滚动条的 TextView。然而,至少有一个警告。当使用单个参数创建 TextView 时
new TextView(Context)
构造函数通过添加额外参数的其他构造函数进行伸缩。这些构造函数之一定义如下:
public TextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
第三个参数com.android.internal.R.attr.textViewStyle 是一个Android 内部样式,它将从主题中获取一个默认的textViewStyle。我建议的调用使用零作为第三个参数,因此主题中定义的任何 textViewStyle 都不会被应用。
对此的合理解决方法可能是执行以下操作:
tv = new TextView(this, null, android.R.attr.textViewStyle, R.style.ViewWithScrollbars);
很遗憾,如果主题中定义了第三个参数 (defStyleAttr),则不使用第四个参数 (defStyleRes)。因此,滚动条不会出现。
如果您使用textViewStyle,那么您将不得不进行调整或仅使用以下方法。
适用于所有 API
使用上面的样式“ViewWithScrollBars”,我们可以定义一个ContextThemeWrapper,它将滚动条安装到用于创建TextView的主题中。
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.ViewWithScrollbars); // "this" is the Activity
tv = new TextView(ctw);
请参阅 Chris Banes 的一篇题为 "Theme vs Style" 的文章,该文章解释了主题叠加的工作原理。
以下将所有这些放在一起。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = new TextView(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// This will actually work for API 21 and above.
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.ViewWithScrollbars);
tv = new TextView(ctw);
} else {
tv = new TextView(this, null, 0, R.style.ViewWithScrollbars);
}
tv.setText(R.string.lorem);
tv.setTextColor(Color.parseColor("red"));
tv.setTextSize(12);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setMaxLines(7);
tv.setTag(View.generateViewId());
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setEllipsize(TextUtils.TruncateAt.END);
tv.setVisibility(View.VISIBLE);
tv.setVerticalScrollBarEnabled(true);
tv.setScroller(new Scroller(this));
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setScrollBarFadeDuration(0);
((RelativeLayout) findViewById(R.id.layout)).addView(tv);
}
}