摘自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.