以编程方式获取TextView大小(Get TextView size programmatically)

编程入门 行业动态 更新时间:2024-10-20 01:30:02
以编程方式获取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(); } });

更多推荐

本文发布于:2023-07-31 02:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大小   方式   programmatically   TextView   size

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!