动态设置textView 位置

来源:互联网 发布:java导出excel的方法 编辑:程序博客网 时间:2024/06/06 06:39

有的时候需要在 整个屏幕中 居中显示textView,而此时的textView的最外层还有几个控件,导致设置xml无法居中显示(只有除了其他控件外的地方,以此居中),所以需要动态获取此时的高度,在渲染完成后获取。

private void getLocation() {<span style="white-space:pre"></span>//监听textView外的控件listView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {listHeight = listView.getMeasuredHeight();//获取 该控件高度listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);//关闭监听,否则程序会崩溃,不断监听getListViewHeight(listHeight);}});}private void getListViewHeight(int height) {DisplayMetrics dm = getResources().getDisplayMetrics();int xheight = dm.heightPixels;//获取总屏幕高度int x;x = xheight / 2 - (xheight - height);//获取textView 距离 外层控件的 距离,此距离是 相当于总屏幕的中间,距离上边控件的距离RelativeLayout.LayoutParams p1 = (android.widget.RelativeLayout.LayoutParams) error_text.getLayoutParams();p1.topMargin = x;//设置像素p1.addRule(RelativeLayout.CENTER_HORIZONTAL);//设置 水平居中textView.setLayoutParams(p1);}


0 0