開發中常常須要實現圖標配文字的菜單項,如圖
佈局
通常的實現思路是每個菜單項由一個LinearLayout
包裹一個ImageView
和一個TextView
實現。可是這樣作會增長佈局的嵌套層數,另外一個實現思路是經過TextView
的drawableLeft
屬性來實現此效果,經過代碼設置邊距和圖片大小。
代碼以下:this
` TextView tvScanCode = (TextView) headerView.findViewById(R.id.tv_scan_code); Drawable drawableScan = ContextCompat.getDrawable(this, R.drawable.ic_nav_scan); drawableScan.setBounds(0, 0, 40, 40); tvScanCode.setCompoundDrawables(drawableScan, null, null, null); TextView tvFeedback = (TextView) headerView.findViewById(R.id.tv_feed_back); Drawable drawableFeed = ContextCompat.getDrawable(this, R.drawable.ic_nav_deedback); drawableFeed.setBounds(0, 0, 40, 40); tvFeedback.setCompoundDrawables(drawableFeed, null, null, null); TextView tvAbout = (TextView) headerView.findViewById(R.id.tv_about); Drawable drawableAbout = ContextCompat.getDrawable(this, R.drawable.ic_nav_about); drawableAbout.setBounds(0, 0, 40, 40); tvAbout.setCompoundDrawables(drawableAbout, null, null, null);`