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;
}
}