获取TextView的大小编程
问题描述:
我的代码:获取TextView的大小编程
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Uri uri = Uri.parse("Home");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.mesage_linear1);
final TextView message = new TextView(getActivity());
number_view.setText("Long Text");
int m_width = message.getMeasuredWidth();
int m_height = message.getMeasuredHeight();
Toast.makeText(getActivity(),"Height : "+m_height+"\nWidth : "+m_width,Toast.LENGTH_LONG).show();
return rootView;
}
我想要得到的编程方式创建TextView
的高度和宽度。
输出为高:0和宽度:0
答
在这一点上View
尚未制定出来呢。您必须手动测量它(通过View.measure()
)或等待,直到它被布局:
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int height = textView.getHeight();
int width = textView.getWidth();
}
});
答
TextView tv=(TextView)findViewById(R.id.text);
tv.setText("Android");
tv.measure(0, 0);
tv.getMeasuredWidth();
tv.getMeasuredHeight();
tv.getTextSize();
加上'rootView' –
里面你'TextiVew'你需要测量的高度和第一宽度。 message.measure(MeasureSpec.AT_MOST,MeasureSpec.AT_MOST); int m_width = message.getMeasuredWidth(); int m_height = message.getMeasuredHeight(); –