当页面有多个按钮或者监听器时,可以用以下代码方式汇总设置:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { //此处使用View.OnClickListener接口 private Button btn_down; private Button btn_up; private ScrollView scrollView; private TextView txt_show; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { btn_down = (Button) findViewById(R.id.btn_down); btn_up = (Button) findViewById(R.id.btn_up); scrollView = (ScrollView) findViewById(R.id.scrollView); txt_show = (TextView) findViewById(R.id.txt_show);
//必须为按钮设置(this)监听器 btn_down.setOnClickListener(this); btn_up.setOnClickListener(this); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 100; i++) { sb.append("呵呵 * " + i + " "); } txt_show.setText(sb.toString()); } @Override public void onClick(View v) { switch (v.getId()) { //在此处使用Switch来统一管理; case R.id.btn_down: scrollView.fullScroll(ScrollView.FOCUS_DOWN); break; case R.id.btn_up: scrollView.fullScroll(ScrollView.FOCUS_UP); break; }