2017-04-25 62 views
0

我的代碼:獲取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

+0

加上'rootView' –

+0

裏面你'TextiVew'你需要測量的高度和第一寬度。 message.measure(MeasureSpec.AT_MOST,MeasureSpec.AT_MOST); int m_width = message.getMeasuredWidth(); int m_height = message.getMeasuredHeight(); –

回答

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(); 
    } 
}); 
0
TextView tv=(TextView)findViewById(R.id.text); 
    tv.setText("Android"); 
    tv.measure(0, 0); 
    tv.getMeasuredWidth(); 
    tv.getMeasuredHeight(); 
    tv.getTextSize();