main.xml
宣告一個Scroll view... 然後裡面用一個linear layout
====================================================
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" // 水平方向 android:padding="6dp"> <Button android:id="@+id/btAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onAddClick" android:text="@string/text_btAdd" /> <TextView android:id="@+id/tvCount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" /> </LinearLayout> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="6dp"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="6dp" android:orientation="vertical" /> </ScrollView> </LinearLayout>
==================================================================================
main.java
=====================================================================================
public class MainActivity extends AppCompatActivity { private TextView tvCount; private ScrollView scrollView; private LinearLayout linearLayout; private int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); tvCount.setText(String.valueOf(count)); // 初始值 } private void findViews() { tvCount = (TextView) findViewById(R.id.tvCount); scrollView = (ScrollView) findViewById(R.id.scrollView); linearLayout = (LinearLayout) findViewById(R.id.linearLayout); // scrollview 裡面的linear layout } public void onAddClick(View view) { count++; tvCount.setText(String.valueOf(count)); // 更新目前的 count TextView textView = new TextView(this); // 宣告並初始一個Textview textView.setText(String.valueOf(count)); // textview set text linearLayout.addView(textView); // 增加到linearlayout scrollView.post(new Runnable() { // 更新scroll view.. 使用 Runnable @Override public void run() { scrollView.fullScroll(View.FOCUS_DOWN); } }); } }
沒有留言:
張貼留言