非常简单的ScrollView应用,适合新手练习
一. scroll_view_main_activity.xml布局代码:
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
tools:context=".ScrollViewDemo.ScrollViewActivity">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/main_title" />
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_content"
android:layout_below="@id/main_title" />
</RelativeLayout>
主布局RelativeLayout中添加ScrollView组件,通过一个TextView作为标头,一个TextView作为存储一段文字。
二. ScrollViewActivity.java代码
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.simpletest.R;
public class ScrollViewActivityextends AppCompatActivity {
private TextViewmainTitle;
private TextViewmainContent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scroll_view_main_activity);
// 获取TextView组件
mainTitle = findViewById(R.id.main_title);
// 获取TextView组件
mainContent = findViewById(R.id.main_content);
// 文字注入
mainTitle.setText("ScrollView Demo");
// 如果大量文字注入,常用StringBuilder或者StringBuffer
StringBuffer stringBuffer =new StringBuffer("一个简单的ScrollView演示");
for(int i =0; i <20; i++) {
stringBuffer.append("演示message的第" + i +"行");
}
}
}
网友评论