以编程方式获取TextView大小(Get TextView size programmatically)
我的代码:
@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
My Code:
@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; }I want to get the height and width of the programmatically created TextView.
Output is Height : 0 and Width : 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(); } });At that point the View hasn't been laid out yet. You have to manually measure it (via View.measure()) or to wait until it is laid out:
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { textView.getViewTreeObserver().removeOnGlobalLayoutListener(this); int height = textView.getHeight(); int width = textView.getWidth(); } });更多推荐
发布评论