用代码实现FrameLayout

摘自http://javatechig.com/android/android-framelayout-example

Android operating system provides list of API’s to create FrameLayout programmatically. Although most developers prefers to have layout as xml, but certain situations you might require view to be created programmatically. The following code snippet will show you how to achieve the same result as shown in the image above, from code.

Just add the following code to your activity onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Initializing imageView
    ImageView imageView = new ImageView(this);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setImageResource(R.drawable.photo);
    imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
    			LayoutParams.MATCH_PARENT));

    TextView textView1 = new TextView(this);
    textView1.setText("Fanny Hands Lane, London");
    textView1.setTextSize(22);
    textView1.setGravity(Gravity.CENTER_HORIZONTAL);
    textView1.setTextColor(Color.parseColor("#fcfcfc"));
    textView1.setBackgroundColor((Color.parseColor("#00000c")));
    textView1.setPadding(10,10,10,10);
	LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 
				Gravity.CENTER_HORIZONTAL);
    lp1.setMargins(0,20,0,0);
    textView1.setLayoutParams(lp1);

    TextView textView2 = new TextView(this);
    textView2.setTextSize(18);
    textView2.setGravity(Gravity.RIGHT|Gravity.BOTTOM);
    textView2.setText("26/Jan/2014");
    textView2.setTextColor(Color.WHITE);
    textView2.setPadding(10,10,10,10);
    textView2.setBackgroundColor(Color.BLACK);
    LayoutParams lp2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 
    			Gravity.BOTTOM|Gravity.RIGHT);
    textView2.setLayoutParams(lp2);

    //Initializing frame layout
    FrameLayout framelayout = new FrameLayout(this);
    framelayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
    			LayoutParams.MATCH_PARENT));

    //Adding views to FrameLayout
    framelayout.addView(imageView);
    framelayout.addView(textView1);
    framelayout.addView(textView2);

     setContentView(framelayout);
}

Key Notes

1.  LayoutParams 是指FrameLayout.LayoutParams。
2. The visibility of all child views added to FrameLayout, can be controlled programmatically by using setVisiblity() method.
3. LayoutParams are used by views to tell their parents how they want to be laid out. The base LayoutParams class just describes how big the view wants to be for both width and height.
4. The order in which the views are added to FrameLayout is important. Views may be hidden beneath, if we some other view added on top of it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值