Hack 13 在onCreate()中获得view的宽高

  当开发中需要控件的宽度和高度时,我们可能首先想到view的getHeight( ) 和getWidth( ),但 在onCreate()中调用这两个方法时,高度和宽度返回0,因为在onCreate()中正在通过LayoutInflater加载xml布局,还没来得及测量他们的尺寸,得不到view的宽高,

依文档解释:


    layout绘制是两个过程:测试view的尺寸和布置view的位置,测试实现measure(int ,int)依据view树从上往下依次进行,测试完成,view保存其measure信息,布置view通过layout(int,int,int,int)也是依据view树从上往下依次进行,依据view的尺寸来分配view的控件和位置。

其实就是两点

1.先确定view的大小尺寸,位置等信息

2.依据得到的信息排列布局

当加载布局的时候才能得到view的宽度和高度,先调用onCreate()才加载布局,因此,得到的宽和高为0,就如同我们包饺子,饺子馅还没准备好,就不知道实际的饺子有多大。

  可以用 view的post(Runnable r)方法解决,把一个线程放到消息队列,布局加载完,线程会在主线程执行,得到view的宽度和高度

package com.manning.androidhacks.hack013;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private TextView mTextView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mTextView = (TextView) findViewById(R.id.my_text_view);

		mTextView.post(new Runnable() {

			@Override
			public void run() {
				String size = String.format("TextView's width: %d, height: %d", mTextView.getWidth(), mTextView.getHeight());
				Toast.makeText(MainActivity.this, size, Toast.LENGTH_SHORT).show();

			}
		});
	}
}

原文:



提示:view源码中有很多post()的用法,可以查找post,看看其用法,理解了就不会滥用

Android页面顶部有tab标签,每个tab标签有对应的列表数据,但是加载数据后,列表数据不能上下滚动,activity代码: public class ActivityTaskCenter extends Activity { private ImageView imgBack; private Button btnRefresh; private TextView tvTitle; private LinearLayout tabLayout; private HorizontalScrollView tabScrollView; private SwipeMenuListView taskListView; private List<Map<String,Object>> dataList = new ArrayList<>(); private final static int SCANNIN_GREQUEST_ORDER = 1000; private String userid = ""; private String whseid = ""; private int currentTab = 0; private TaskCenterAdapter taskCenterAdapter = null; public ActivityTaskCenter.TaskCenterAdapter getMyActivityTaskCenter() { return taskCenterAdapter; } public List<Map<String, Object>> getTaskCenterList() { return dataList; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); imgBack = this.findViewById(R.id.id_title_btnBack); btnRefresh = this.findViewById(R.id.id_title_btnRefrush); tvTitle = this.findViewById(R.id.id_title_tip); tabScrollView = findViewById(R.id.tabScrollView); tabLayout = findViewById(R.id.tabLayout); taskListView = findViewById(R.id.id_taskcenter_listview); initView(); // 初始化标签栏 initTabs(); initEvent(); // 延迟加载确保布局已完成 taskListView.post(() -> loadData(0)); taskListView.setScrollContainer(true); taskListView.requestLayout(); } private void initView(){ try{ tvTitle.setText("任务中心"); btnRefresh.setVisibility(View.GONE); //初始化等待界面 Config.m_pDoalog = new ProgressDialog(ActivityTaskCenter.this); Config.m_pDoalog.setProgressStyle(ProgressDialog.STYLE_SPINNER); userid = SharedPreferencesUtil.GetData(getApplication(), "username", "").toString(); whseid = SharedPreferencesUtil.GetData(getApplication(), "whseid", "").toString(); taskCenterAdapter = new TaskCenterAdapter(); taskListView.setAdapter(taskCenterAdapter); taskListView.setNestedScrollingEnabled(true); }catch (Exception e){ e.printStackTrace(); } } private void initTabs() { String[] tabTitles = {"未领取", "已领取", "已完成"}; int activeColor = getResources().getColor(R.color.color_yelloworange); int inactiveColor = getResources().getColor(android.R.color.black); for (int i = 0; i < tabTitles.length; i++) { TextView tab = new TextView(this); tab.setTag(i); tab.setText(tabTitles[i]); tab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); tab.setGravity(Gravity.CENTER); tab.setPadding(32, 16, 32, 16); // 设置初始状态 if (i == currentTab) { tab.setBackgroundColor(getResources().getColor(android.R.color.white)); tab.setTextColor(activeColor); tab.getPaint().setFakeBoldText(true); } else { tab.setBackgroundColor(getResources().getColor(R.color.color_yelloworange)); tab.setTextColor(inactiveColor); } LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); tab.setLayoutParams(params); // 设置点击监听 tab.setOnClickListener(v -> { int tabIndex = (int) v.getTag(); switchTab(tabIndex); loadData(tabIndex); currentTab = tabIndex; }); tabLayout.addView(tab); } } private void switchTab(int tabIndex) { // 更新UI样式 for (int i = 0; i < tabLayout.getChildCount(); i++) { TextView tab = (TextView) tabLayout.getChildAt(i); if (i == tabIndex) { tab.setBackgroundColor(getResources().getColor(android.R.color.white)); tab.setTextColor(getResources().getColor(R.color.color_yelloworange)); tab.getPaint().setFakeBoldText(true); } else { tab.setBackgroundColor(getResources().getColor(R.color.color_yelloworange)); tab.setTextColor(getResources().getColor(android.R.color.white)); tab.getPaint().setFakeBoldText(false); } } // 确保选中的标签可见 tabScrollView.smoothScrollTo(tabLayout.getChildAt(tabIndex).getLeft(), 0); currentTab = tabIndex; } private int dp2px(int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); } private void initEvent(){ try { imgBack.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ActivityTaskCenter.this.finish(); } }); } catch (Exception e) { throw new RuntimeException(e); } } private final Handler TaskCenterHandle = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { try{ switch (msg.what){ case SCANNIN_GREQUEST_ORDER: Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),47, DomUtil.doc2xmlStr(doc)); break; } }catch (Exception e){ e.printStackTrace(); Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } return true; } }); private void loadData(int tabIndex) { dataList.clear(); switch (tabIndex) { case 0: // 未领取 getLoadData(47); break; case 1: // 已领取 getLoadData(48); break; case 2: // 已完成 getLoadData(49); break; } } public void refresh(){ getLoadData(currentTab); } public void playErrorSound(Context context) { MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.beep); if (mediaPlayer != null) { mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); // 播放完成后释放资源 } }); mediaPlayer.start(); } } public class TaskCenterAdapter extends BaseAdapter { @Override public int getCount() { return dataList == null ? 0 : dataList.size(); } @Override public Object getItem(int i) { return dataList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ convertView = View.inflate(getApplicationContext(),R.layout.item_listview4taskcenter,null); new ActivityTaskCenter.TaskCenterAdapter.ViewHolderForOutBound(convertView); } ViewHolderForOutBound holder = (ViewHolderForOutBound) convertView.getTag(); final Map<String, Object> item = (Map<String, Object>) getItem(position); holder.task_orderno.setText(item.get("receiptkey").toString()); holder.task_adddate.setText(item.get("adddate").toString()); holder.task_tasktype.setText(item.get("task_type").toString()); holder.task_status.setText(item.get("status").toString()); holder.task_customer.setText(item.get("company").toString()); holder.task_pre_qty.setText(item.get("pre_qty").toString()); holder.task_goods_count.setText(item.get("goods_count").toString()); holder.btnReceive.setTag(position); convertView.setFocusable(true); convertView.setClickable(true); return convertView; } class ViewHolderForOutBound{ private TextView task_orderno; private TextView task_adddate; private TextView task_tasktype; private TextView task_status; private TextView task_customer; private TextView task_pre_qty; private TextView task_goods_count; private Button btnReceive; public ViewHolderForOutBound(View view){ task_orderno = (TextView) view.findViewById(R.id.id_taskcenter_receiptkey); task_adddate = (TextView) view.findViewById(R.id.id_taskcenter_adddate); task_tasktype = (TextView) view.findViewById(R.id.id_taskcenter_tasktype); task_status = (TextView) view.findViewById(R.id.id_taskcenter_status); task_customer = (TextView) view.findViewById(R.id.id_taskcenter_customer); task_pre_qty = (TextView) view.findViewById(R.id.id_taskcenter_pre_qty); task_goods_count = (TextView) view.findViewById(R.id.id_taskcenter_goods_count); btnReceive = (Button) view.findViewById(R.id.btn_task_claim); btnReceive.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { int position = (int) view.getTag(); // 从 tag 中获取 position Map<String, Object> item = (Map<String, Object>) dataList.get(position); String receiptKey = item.get("receiptkey").toString(); String task_type = item.get("task_type").toString(); int msgwhat = 50; if(task_type.equals("验货任务")){ msgwhat = 50; } else if (task_type.equals("拣货任务")) { msgwhat = 51; }else if (task_type.equals("发货任务")) { msgwhat = 52; } Config.m_pDoalog.setMessage("请稍等..."); Config.m_pDoalog.setIndeterminate(false); Config.m_pDoalog.setCancelable(false); Config.m_pDoalog.show(); Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); licUserEle.addContent(new Element("orderkey").addContent(receiptKey)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),msgwhat, DomUtil.doc2xmlStr(doc)); } }); view.setTag(this); } } } public void showData(List<Map<String, Object>> dataList){ this.dataList = dataList; taskCenterAdapter.notifyDataSetChanged(); } public void getLoadData(int msgwhat){ Config.m_pDoalog.setMessage("请稍等..."); Config.m_pDoalog.setIndeterminate(false); Config.m_pDoalog.setCancelable(false); Config.m_pDoalog.show(); Document doc = new Document(new Element("NewDataSet")); Element rootEle = doc.getRootElement(); Element licUserEle = new Element("RecCheck"); licUserEle.addContent(new Element("userid").addContent(userid)); licUserEle.addContent(new Element("whseid").addContent(whseid)); rootEle.addContent(licUserEle); PostWebservices.webSend(ActivityTaskCenter.this,new HandlerMsg(ActivityTaskCenter.this),msgwhat, DomUtil.doc2xmlStr(doc)); } public void setCloseProDialog(){ Config.m_pDoalog.hide(); } } activity_task代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#F5F5F5"> <!-- 固定顶部的标签栏 --> <HorizontalScrollView android:id="@+id/tabScrollView" android:layout_width="match_parent" android:layout_height="40dp" android:fillViewport="true" android:scrollbars="none" android:background="@color/color_yelloworange"> <LinearLayout android:id="@+id/tabLayout" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" /> </HorizontalScrollView> <com.likelic.wmsassistantbyadp.baoyz.swipemenulistview.SwipeMenuListView.SwipeMenuListView android:id="@+id/id_taskcenter_listview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:divider="#EEEEEE" android:dividerHeight="2px" android:scrollbars="vertical" android:nestedScrollingEnabled="true"/> </LinearLayout>
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值