px与pt
- px像素
- pt:point,标准的长度单位,1pt=1/72英寸,一般用于印刷业
dp与sp(常用)
- dip(device independent pixels),设备独立像素,不同设备有不同的显示效果,与设备硬件有关,不依赖像素
- dp :同dip
- sp:scaled pixels(放大像素),主要用于字体显示 best for textsize
LayoutParams
相当于一个Layout的信息包,封装了Layout的位置、高、宽等信息。(仅用于java代码的书写)
package com.example.mylayoutparams;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
LinearLayout linearLayout = new LinearLayout(this);
//占满全屏
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(layoutParams);
TextView textView = new TextView(this);
textView.setText("我是文本");
textView.setBackgroundColor(0xffff0000);
//若直接写数字,则为px像素
LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
300);
//1.
// textView.setLayoutParams(textLayoutParams);
// linearLayout.addView(textView);
//2.设置textView的同时,传入textLayoutParams
linearLayout.addView(textView,textLayoutParams);
setContentView(linearLayout);
}
}
ViewPages
//布局服务
// 一个用于加载布局的系统服务,就是实例化与Layout XML文件对应的View对象,不能直接使用, 需
// 要通过getLayoutInflater( )方法或getSystemService( )方法来获得与当前Context绑定的 LayoutInflater实例
LayoutInflater lf = getLayoutInflater().from(this);
// public View inflate (int resource, ViewGroup root, boolean attachToRoot)该方法的三个参数依次为:
//要加载的布局对应的资源id
//为该布局的外部再嵌套一层父布局,如果不需要的话,写null就可以了!
//是否为加载的布局文件的最外层套一层root布局,不设置该参数的话, 如果root不为null的话,则默认为true
// 如果root为null的话,attachToRoot就没有作用了!
// root不为null,attachToRoot为true的话,会在加载的布局文件最外层嵌套一层root布局;
// 为false的话,则root失去作用! 简单理解就是:是否为加载的布局添加一个root的外层容器~!
View view1 = lf.inflate(R.layout.layout1,null);
View view2 = lf.inflate(R.layout.layout2, null);
View view3 = lf.inflate(R.layout.layout3, null);
List<View> viewList = new ArrayList<>();
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
ViewPager viewPager = findViewById(R.id.vp);
MyAdapter myAdapter = new MyAdapter(viewList);
viewPager.setAdapter(myAdapter);