gpt4 book ai didi

Android以编程方式获取 View 的宽度

转载 作者:IT老高 更新时间:2023-10-28 23:12:05 24 4
gpt4 key购买 nike

我以编程方式创建了 TextView,如下所示:

                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();

但是 mTextView.getWidth() 总是返回 0

如果我尝试:

mTextView.getLayoutParams().width

返回LayoutParams类中的LayoutParams对应值(-1或-2)

如何获取 View 的宽度?

编辑我需要在这里做:

            @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);

}

编辑解决方案我从@androiduser的回答中使用了这个:

mTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();

问题解决了!

最佳答案

我使用了这个解决方案:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
// Ensure you call it only once
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

// Here you can get the size :)
}
});

关于Android以编程方式获取 View 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19633318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com