Android面试宝典Android开发Android开发

Android面试之布局

2016-09-25  本文已影响138人  cooperise

Android中的五种布局

a. Frameayout: (堆栈布局) 布局中的View都会以层叠方式显示
b. LinearLayout: (线性布局) 将多个View水平或垂直排列
c. RelativeLayout: (相对布局) 可以通过确定两个或多个组件的相对位置来摆放组件
d. TableLayout: (表格布局) 将View按表格形式排列
e. AbsoluteLayout: (绝对布局) 可以设置View的绝对坐标(无法适应屏幕分辨率变化)

ps: 谷歌约束控件(ConstraintLayout)扁平化布局

xmlns:android ="http://schemas.android.com/apk/res/android" 中的xmlns:android是什么意思,它的值可以任意设置吗?

xmlns:android是XML文件中的命名空间,为了防止属性冲突,它的值不允许任意设
置。xmlns:android的值必须以"http://schemas.android.com/apk/res/" 开头,后面的部分表示定义属性的R.java文件所在的包名。

LinearLayout能不能实现水平方向的左对齐、居中对齐和右对齐?

不行,当LinearLayout设置orientation=“horizontal”时,其layout_gravity属性只有在垂直(如bottom、center_vertical等)方向的值才起作用。

ps: 最方便的方法是使用FrameLayout

如何获取LinearLayout的宽度和高度

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
// measure 方法的参数值都设为0即可
linearlayout.measure(0, 0);
int width = linearlayout.getMeasureWidth();
int height = linearlayout.getMeasureHeight();

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
int width = linearlayout.getLayoutParams().width;
int height = linearlayout.getLayoutParams().height;

在RelativeLayout布局中可以设置标签的android:layout_toLeftOf、android:layout_toRightOf等属性确定组件的相对位置,那么如何使用Java代码来完成这些工作?

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout);
Button button = (Button) getLayoutInflater().inflate(R.layout.button, null);
// 创建一个LayoutParams对象
RelativeLayout.LayoutParams layoutParams = 
new RelativeLayout.LayoutParams(ViewGroup.LayoutpParams.WRAP_CONTENT, 
            ViewGroup.LayoutpParams.WRAP_CONTENT);
// 设置android:layout_below属性
layoutParams.addRule(RelativeLayout.BELOW, R.id.button1);
// 设置android:layout_centerInParent属性
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
button.setLayoutParams(layoutParams);
relativelayout.addView(button);

如何将当前界面的可视组件以同样的相对位置和大小保存在png图像文件中(截图)?

View view = getLayoutInfater().inflate(R.layout.main, null);
// 打开图像缓存
view.setDrawingCacheEnabled(true);
// 必须要调用measure和layout方法才能成功保存截图文件
// 测量View的大小
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
      MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// 发送位置和尺寸到View及其所有的子View
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
try{
   // 获取可视化组件的截图
   Bitmap bitmap = view.getDrawingCache();
   // 将截图保存在SD卡根目录的test.png图像文件中
   FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
   // 将Bitmap对象中的图像数据压缩成png格式的图像数据
   bitmap.compress(CompressFormat.PNG, 100, fos);
   fos.close();
}catch(Exception e){
}

android:padding属性和android:layout_margin属性的区别是什么?

android:padding是用于设置View中的内容距View边缘的距离(内边距),而android:layout_margin属于用于设置View距离其他View或父容器边缘的距离(外边距)。

android:gravity属性和android:layout_gravity属性的区别是什么?

android:gravity指定了View中内容的位置,android:layout_gravity指定了当前View在父View中的位置。

上一篇下一篇

猜你喜欢

热点阅读