Android关于布局的经典面试题及解答(一)

时间:2022-10-04 17:49:12

1、RelativeLayout中如何获取控件相对于屏幕的坐标?

用View.getLocationOnScreen()方法。

2、如何用代码给RelativeLayout中的控件添加布局属性?

用addRule()的方法。

textView = (TextView)findViewById(R.id.text_view);
RelativeLayout.LayoutParams para = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
para.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView.setLayoutParams(para);

前提是textView的母布局是个RelativeLayout。

3、GridLayout和TableLayout的区别,有变化。

参见 http://blog.csdn.net/runninglion/article/details/10813929 

4、如何实现截图?

利用/**
* 若要截图,在getDrawingCache前必须要measure和layout
* */
int widthMeasure = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int heightMeasure = widthMeasure;
parent.measure(widthMeasure, heightMeasure);
parent.layout(0, 0, widthMeasure, heightMeasure);

这是骗人的,根本截不了。正确如下:

private void getDrawBitmap(){
View parent = this.getWindow().getDecorView();
//getLayoutInflater().inflate(R.layout.activity_main, null);
if(parent == null){
return;
}
parent.setDrawingCacheEnabled(true);
//parent.buildDrawingCache();
/**
* 若要截图,在getDrawingCache前必须要measure和layout
* */
int widthMeasure = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int heightMeasure = widthMeasure;
parent.measure(widthMeasure, heightMeasure);
parent.layout(0, 0, widthMeasure, heightMeasure);
Bitmap b = parent.getDrawingCache();
saveBitmap(b,"/storage/sdcard0/Download", "ttt.jpg");

}
/**
* @param b
* @param path
* @param name
* 保存图片
*/
private void saveBitmap(Bitmap b, String path,String name){
File file = new File(path);
if (!file.exists()){
file.mkdir();
}
try {
FileOutputStream fos = new FileOutputStream(path + "/" + name);
b.compress(CompressFormat.JPEG, 85, fos);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

参见: http://blog.csdn.net/developer_jiangqq/article/details/12164239 http://whithin.blog.51cto.com/690417/1159072

5、如何设置Activity或View的背景颜色为渐变色??

//设置Activity从上到下的渐变色
GradientDrawable gradientDraw = new GradientDrawable(Orientation.TOP_BOTTOM,
new int[]{Color.RED, Color.YELLOW});
getWindow().setBackgroundDrawable(gradientDraw);

效果:

Android关于布局的经典面试题及解答(一)

更多关于GradientDrawable的用法: http://blog.csdn.net/qq315297923/article/details/8539736 


6、android 的layout_weight的含义:

表示view的原布局宽度再加上剩余空间的程度的比重,所以当两个View的宽度设为wrap_content和match_parent时设同样的weight得效果刚好相反的原因。

参见:

http://www.xiaoyunduo.org/article/97/ 

http://blog.csdn.net/jincf2011/article/details/6598256  

http://yulongsheng.blog.51cto.com/3804293/1260876