Reputation: 1
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
Upvotes: 0
Views: 2055
Reputation: 41
TextView tv=(TextView)findViewById(R.id.text);
tv.setText("Android");
tv.measure(0, 0);
tv.getMeasuredWidth();
tv.getMeasuredHeight();
tv.getTextSize();
Upvotes: 0
Reputation: 62189
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();
}
});
Upvotes: 1