我的代码:
@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
答案 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();
}
});
答案 1 :(得分:0)
TextView tv=(TextView)findViewById(R.id.text);
tv.setText("Android");
tv.measure(0, 0);
tv.getMeasuredWidth();
tv.getMeasuredHeight();
tv.getTextSize();