ho TextView creato a livello di codice, così:Android di vista ottenere a livello di codice creato
TextView mTextView = new TextView(getApplicationContext());
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
mTextView.setText(mText);
mTextView.setLayoutParams(params);
mTextView.setPadding(2, 2, 2, 2);
mTextView.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(mTextView);
textViewsWidth = mTextView.getWidth();
Ma mTextView.getWidth() restituisce sempre 0
E se provo:
mTextView.getLayoutParams().width
Restituisce il valore corrispondente di LayoutParams nella classe LayoutParams (-1 o -2)
Come posso ottenere la larghezza della vista?
EDIT ho bisogno di fare questo qui:
@Override
public void onPostExecute(Hashtable<String, Integer> hash){
final ScrollView tagMapScroll = (ScrollView) findViewById(R.id.tagMapScroll);
final LinearLayout tagMap = (LinearLayout) findViewById(R.id.tagMap);
final ArrayList<Integer> arr = new ArrayList<Integer>(hash.values());
final Enumeration<String> e = hash.keys();
int index = 0;
int textViewsWidth = 0;
while(e.hasMoreElements()){
final TextView tV = new TextView(getApplicationContext());
tV.setTextColor(Color.parseColor("#666666"));
tV.setText(Html.fromHtml(randomColor() + e.nextElement()));
tV.setTextSize(arr.get(index));
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
tV.setLayoutParams(params);
tV.setPadding(2, 2, 2, 2);
tV.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(tV);
textViewsWidth += tV.getWidth();
index++;
}
tagMapScroll.setVisibility(ScrollView.VISIBLE);
}
EDIT SOLUZIONE ho usato questo da @ di androiduser risposta:
mTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();
Problema risolto!
Non è possibile ottenere la larghezza della vista, fino alla 'onMeasure' è stato chiamato per la vista. Fare riferimento: http://stackoverflow.com/q/3591784/827110 –
Ora se ci dici di cosa hai bisogno per la larghezza? Forse qualcuno può proporre una soluzione. –
Stai chiamando getWidth() troppo presto. L'interfaccia utente non è stata ancora dimensionata e visualizzata sullo schermo. –