ScrollView用法
package com.example.scrollview; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; public class MainActivity extends Activity { private ScrollView sView; private LinearLayout linearLayout; private Button button; private TextView textView; private Handler myHandler = new Handler(); //当前滚屏的高度 private int sHeight ; private Intent myIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sView = (ScrollView)findViewById(R.id.scrollView); linearLayout = (LinearLayout)findViewById(R.id.linearLayout); button = (Button)findViewById(R.id.button); textView = (TextView)findViewById(R.id.textView); sHeight = sView.getHeight(); button.setOnClickListener(new myOnclickListener()); } /** * button事件: * 1.点击button在linearlayout中动态添加textView和button * 2.触发ScrollView的滚屏操作,滚动到最新添加的button处 * */ class myOnclickListener implements OnClickListener{ int index = 0; @Override public void onClick(View v) { LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); TextView addText = new TextView(MainActivity.this); addText.setText("textView"+index); Button addButton = new Button(MainActivity.this); addButton.setText("button"+index); addButton.setId(index++); linearLayout.addView(addText, linearLayoutParams); linearLayout.addView(addButton, linearLayoutParams); myHandler.post(mScrollToButton); } } private Runnable mScrollToButton = new Runnable() { @Override public void run() { //linearLayout的总高度 System.out.println("linearLayout.getMeasuredHeight() =>"+linearLayout.getMeasuredHeight()); //定位:位置 = 总高度 - 当前屏幕的高度 int off = linearLayout.getMeasuredHeight() - sHeight; if(off > 0){ //向下滚屏 sView.scrollBy(0, off); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28