Android里所有的UI控件都有一个共同的基类View。View里有一种类型是可以包含其它一些子控件的,它就是ViewGroup。而ViewGroup的子类Layout更加明确地定义了自己的功能:包含一些子控件并对它们排版,比如LinearLayout。Layout类包括:LinearLayout、RelativeLayout、TableLayout、DatePicker、TimePicker、Form Stuff、Spinner、AutoComplete、ListView、GridView、Gallery、TabWidget、MapView、WebView等。
Layout可以在xml里定义,可以参考前面的LinearLayout的例子。下面介绍下代码里怎么添加layout:
- package tommy.myandroid;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- public class LayoutActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- LinearLayout ll = new LinearLayout(this);
- ll.setOrientation(LinearLayout.VERTICAL);
- TextView tv = new TextView(this);
- tv.setText("Here is text view");
- EditText ev = new EditText(this);
- ev.setText("Edit text here");
- final int width = LinearLayout.LayoutParams.FILL_PARENT;
- final int height = LinearLayout.LayoutParams.WRAP_CONTENT;
- ll.addView(tv, new LinearLayout.LayoutParams(width, height));
- ll.addView(ev, new LinearLayout.LayoutParams(width, height));
- setContentView(ll);
- }
- }
运行结果:
自定一个组合控件
我们可以自定义一些由一些基本控件组合而成的控件。比如上例中的TextView和EidtText的组合:
- package tommy.myandroid;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.util.AttributeSet;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- class CompoundView extends LinearLayout {
- public CompoundView(Context context) {
- super(context);
- init();
- }
-
- public CompoundView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
-
- private void init() {
- setOrientation(LinearLayout.VERTICAL);
- TextView tv = new TextView(getContext());
- tv.setText("Here is text view");
- EditText ev = new EditText(getContext());
- ev.setText("Edit text here");
- final int width = LinearLayout.LayoutParams.FILL_PARENT;
- final int height = LinearLayout.LayoutParams.WRAP_CONTENT;
- addView(tv, new LinearLayout.LayoutParams(width, height));
- addView(ev, new LinearLayout.LayoutParams(width, height));
- }
- }
- public class LayoutActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new CompoundView(this));
- }
- }
运行的结果和上例一样。不过,如果需要组合的话,最好还是定义在一个xml里,作为一个resource来重用。
阅读(1028) | 评论(0) | 转发(0) |