Android UI编程速查

date: 2013.06.17; modification:2016.09.08

目录:

1 Layout

1.1 线性布局(LinearLayout)

XML:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context=".MainActivity" >

        ...some views...

    </LinearLayout>

相关属性:

android:orientation="vertical" / "horizontal"
android:layout_gravity="top"/"bottom"/"left"/"right"/"center_horizontal"/...
android:layout_weight="1" // 使用该属性时, 尽量相关宽/高设置为0dp, 这样比较容易计算.
                          // 也可其中一些设置为wrap, 另外一些设置该weight

1.2 相对布局()


    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">

        

相关属性:

相对于父级Layout:

android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"

相对于其他控件:

android:layout_above="@id/button3"
android:layout_below="@id/button3"
android:layout_toLeftOf="@id/button3"
android:layout_toRightOf="@id/button3"

与其他控件对齐:

android:layout_alignTop
android:layout_alignBottom
android:layout_alignLeft
android:layout_alignRight

2 控件

2.1 文本框(TextView)

XML:

    <TextView
        android:layout_width="480dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:background="#888888"
        android:text="@string/hello_world" />

JAVA:

    private TextView textView;

    textView = (TextView)findViewById(R.id.textView);
    textView.setText("^_^");

2.2 输入框(EditText)

XML:

    <EditText android:id="@+id/edit_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/edit_message"
            android:maxLines="2" />

JAVA:

    private EditText editText;
    editText = (EditText) findViewById(R.id.edit_text);
    String inputText = editText.getText().toString();

2.3 按钮(Button)

XML:

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select All" />

说明:

JAVA:

    import android.view.View.OnClickListener;

    Button button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(buttonSelectAllListener);

    OnClickListener buttonSelectAllListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Button button = (Button)v;
            if(button.getId() == R.id.button1) {
                Log.d(TAG, "onClick button1\n");
            }
        }
    };

2.4 复选框(CheckBox)

XML:

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox1" />

JAVA方法1(使用通用Listener):

    import android.view.View.OnClickListener;

    private CheckBox checkBox1;
    checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
    checkBox1.setOnClickListener(listener);

    // 点击相应Listener
    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            CheckBox box = (CheckBox)v;
            if(box.getId() == R.id.checkBox1) {  // 用于当listener绑定到多个checkbox时候以做区分.
                Log.d(TAG, "onClick checkBox1\n");
            }
            else {
                Log.d(TAG, "onClick checkBox2\n");
            }
            Log.d(TAG, box.isChecked() ? "Checked" : "UnChecked");
        }
        
    };

JAVA方法2(使用通用OnCheckedChangeListener):

    import android.widget.CompoundButton.OnCheckedChangeListener;

    private CheckBox checkBox1;
    checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
    checkBox1.setOnCheckedChangeListener(listener);

    OnCheckedChangeListener listener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton box, boolean isChecked) {
            if(box.getId() == R.id.checkBox1) {
                Log.d(TAG, "onClick checkBox1\n");
            }
            else {
                Log.d(TAG, "onClick checkBox2\n");
            }
            Log.d(TAG, box.isChecked() ? "Checked" : "UnChecked");
        }
    };

2.5 单选按钮(RadioButton)

XML:

    <RadioGroup
        android1:id="@+id/radioGroup1"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content" >

        <RadioButton
            android1:id="@+id/radio0"
            android1:layout_width="wrap_content"
            android1:layout_height="wrap_content"
            android1:checked="true"
            android1:text="RadioButton0" />

        <RadioButton
            android1:id="@+id/radio1"
            android1:layout_width="wrap_content"
            android1:layout_height="wrap_content"
            android1:text="RadioButton1" />
    </RadioGroup>

JAVA:

    import android.widget.RadioGroup.OnCheckedChangeListener;

    private RadioGroup radioGroup;
    private RadioButton radio0;
    private RadioButton radio1;

    radio0 = (RadioButton)findViewById(R.id.radio0);
    radio1 = (RadioButton)findViewById(R.id.radio1);
    radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
    radioGroup.setOnCheckedChangeListener(radioCheckedChangeListener);

    OnCheckedChangeListener radioCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if(checkedId == radio0.getId()) {
                Log.d(TAG, "radio0 Checked.");
            }
            else if(checkedId == radio1.getId()) {
                Log.d(TAG, "radio1 Checked.");
            }
            else {
                Log.d(TAG, "unKnown Checked.");
            }
        }
    };

2.6 图片(ImageView)

XML:

    <ImageView
        android1:id="@+id/imageView1"
        android1:layout_width="wrap_content"
        android1:layout_height="match_parent"
        android1:scaleType="fitXY"
        android1:src="@drawable/iron3" />

JAVA:

设置图片源:

imageView.setImageResource(R.drawable.jelly_bean);

缩放参数:

fitCenter:    等比例缩放至完全容纳并居中.
fitStart:     等比例缩放至完全容纳并居首.
fitEnd:       等比例缩放至完全容纳并居尾.
fitXY:        不等比例拉伸至刚好完全充满View.
center:       不缩放(可能会截取)并居中.
centerInside: 等比例缩小(但不放大)至完全容纳并居中.
centerCrop:   等比例缩放至短边完全容纳(长边可能被截取).

2.7 进度条(ProgressBar)

XML:

    

JAVA:


    private ProgressBar progressBar;

    // 设置可见性
    progressBar.setVisibility(View.VISIBLE);
    progressBar.setVisibility(View.INVISIBLE);
    progressBar.setVisibility(View.GONE);

    // 设置进度
    progressBar.setProgress(progress);

2.8 列表框(ListView)

2.8.1 基本ListView

XML:


    <ListView android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

JAVA:


    private String[] data = { "Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    MainActivity.this, android.R.layout.simple_list_item_1, data);
    ListView listView = (ListView) findViewById(R.id.list_view);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view,
                                int position, long id) {
            Fruit fruit = fruitList.get(position);
            Toast.makeText(LinearActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();
        }
    });

2.8.2 带图片的ListView

XML:

整体布局同上. 另外再增加列表item的布局:


    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgFruit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/txtvFruitName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dip" />

    </LinearLayout>

JAVA:

java中需要继承ArrayAdapter:


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear);

        initFruits(); // 初始化水果数据
        FruitAdapter adapter = new FruitAdapter(this, R.layout.fruit_item, fruitList);
        ListView listView = (ListView) findViewById(R.id.lstvTest);
        listView.setAdapter(adapter);
    }

    private void initFruits() {
        Fruit apple = new Fruit("Apple", R.mipmap.ic_launcher);
        fruitList.add(apple);
        Fruit banana = new Fruit("Banana", R.mipmap.ic_launcher);
        fruitList.add(banana);
        Fruit orange = new Fruit("Orange", R.mipmap.ic_launcher);
        fruitList.add(orange);
    }

    class Fruit {
        private String name;
        private int imageId;
        public Fruit(String name, int imageId) {
            this.name = name;
            this.imageId = imageId;
        }
        public String getName() {
            return name;
        }
        public int getImageId() {
            return imageId;
        }
    }

    class FruitAdapter extends ArrayAdapter<Fruit> {
        private int resourceId;

        public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects) {
            super(context, textViewResourceId, objects);
            resourceId = textViewResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Fruit fruit = getItem(position); // 获取当前项的Fruit实例
            View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
            ImageView fruitImage = (ImageView) view.findViewById(R.id.imgFruit);
            TextView fruitName = (TextView) view.findViewById(R.id.txtvFruitName);
            fruitImage.setImageResource(fruit.getImageId());
            fruitName.setText(fruit.getName());
            return view;
        }
    }

2.9 AlertDialog


    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
    dialog.setTitle("This is Dialog");
    dialog.setMessage("Something important.");
    dialog.setCancelable(false);
    dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog.show();

2.10 ProgressDialog


    ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    progressDialog.setTitle("This is ProgressDialog");
    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(true);
    progressDialog.show();

3 其他

3.1 删除Eclipse创建的Activity

需要删除的便是Eclipse自动创建出来的代码. 以创建名称为TestActivity为例, Eclipse会添加:

删除以上代码即可.

如果是用Eclipse来build的话, bin/AndroidManifest.xml中相应的标签也要删除.

4 关于控件单位

基本来说在编写 Android 程序的时候, uu尽量将控件或布局的大小指定成 match_parent 或 wrap_content.

如果必须要指定一个固定值, 则使用 dp 来作为单位, 指定文字大小的时候使用 sp 作为单位.