为文本框添加滚动条

可以在xml文件中定义布局,也可以使用代码的方式动态添加布局。下面的例子采用后者的方式:

为文本框添加滚动条,就是在ScrollView 中添加TextView。ScrollView 是一个滚动视图,它只能包含一个子视图,如果需要滚动多个视图,可以让ScrollView 包含一个Layout。

在java 代码中,在onCreate() 方法中新建视图并向其传递上下文参数this,调用addView 方法可以向容器视图添加子视图:

	RelativeLayout layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		layout = (RelativeLayout) findViewById(R.id.layout);
		ScrollView scrollView = new ScrollView(this);
		TextView text = new TextView(this);
		text.setPadding(10, 10, 10, 10);
		text.setTextSize(18);
		text.setText(R.string.text);
		scrollView.addView(text);
		layout.addView(scrollView);
	}


你可能感兴趣的:(android开发)