<
安卓应用构建
>
上一篇

借助 jekyll 搭建静态博客
下一篇

创建 GitHub Pages & 自定域名教程

通过 Android Studio 逐步学习构建 APP。
持续更新,最后更新时间:2019.6.29。

简介

安卓应用是按照 MVC 模式开发的,三个要素分别如下:

方法

利用 Android Studio 进行安卓应用的常用组件功能的实现,首先通过新建 New Project,创建新的Demo项目。
通过更改:
app/manifests/AndroidManifest.xml
app/java/com.example.buttondemo/MainActivity.java
app/layout/activity_main.xml

进行基本功能的实现,以下为个人学习范例。

Button Demo

界面线性分布三个按钮,并实现三个按钮分别显示 TextView,长按 Button1 震动反馈并显示 Toast,实现 Button2 识别 Touch 手势并显示 TextView。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.buttondemo">
    //Vibrate
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.buttondemo;

import android.content.Context;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener,View.OnLongClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Click
        ((Button) findViewById(R.id.btn1)).setOnClickListener(this);
        ((Button) findViewById(R.id.btn2)).setOnClickListener(this);
        ((Button) findViewById(R.id.btn3)).setOnClickListener(this);
        //Touch
        ((Button)findViewById(R.id.btn2)).setOnClickListener(this);
        ((Button)findViewById(R.id.btn2)).setOnTouchListener(this);
        //Long Click
        ((Button) findViewById(R.id.btn1)).setOnLongClickListener(this);
        ((Button) findViewById(R.id.btn2)).setOnLongClickListener(this);
        ((Button) findViewById(R.id.btn3)).setOnLongClickListener(this);
    }

    //Long Click
    @Override
    public boolean onLongClick(View v) {
        if (v.getId() == R.id.btn1) {
            Toast.makeText(MainActivity.this, "Long Press", Toast.LENGTH_SHORT).show();
            //Vibrate
            Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vib.vibrate(500);
        }
        return true;
    }

    //Click
    @Override
    public void onClick(View v) {
        TextView txt1 = (TextView)findViewById(R.id.txt1);
        switch (v.getId()) {
            case R.id.btn1: {
                txt1.setText("Click Button 1");
            } break;
            case R.id.btn2: {
                txt1.setText("Click Button 2");
            } break;
            case R.id.btn3: {
                txt1.setText("Click Button 3");
            } break;
            }
        }

    //Touch
    @Override
    public boolean onTouch(View v, MotionEvent event) {
         if (v.getId() == R.id.btn2) {
             TextView txt = (TextView)findViewById(R.id.txt1);
             if (event.getAction()==MotionEvent.ACTION_DOWN) {
                 txt.setText("Finger Down");
             } else if (event.getAction()==MotionEvent.ACTION_UP) {
                 txt.setText("Finger Up");
             } else if (event.getAction()==MotionEvent.ACTION_MOVE) {
                 txt.setText("Finger Moved");
             }
         }
         return true;
    }
}

activity_main.xml

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

    <TextView android:id="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Demo"/>

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button1"
        android:textAllCaps="false"/>

    <Button android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button2"
        android:textAllCaps="false"/>

    <Button android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button3"
        android:textAllCaps="false"/>

</LinearLayout>

Edit Text

实现单击按钮时,按钮的文本会显示为输入框的内容。

activity_main.xml

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

    <EditText android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"/>

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="Button1"
        android:textAllCaps="false"/>

</LinearLayout>

MainActivity.java

package com.example.edittext;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import  android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit1 = (EditText)findViewById(R.id.edit1);
                Button btn = (Button)findViewById(R.id.btn1);
                btn.setText(edit1.getText());
            }
        });
    }
}

Alert Dialog

创建包含两个选择按钮的 Dialog,点击时显示 Toast 且可以拓展操作。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button1"/>

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.alertdialogdemo;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.DialogInterface;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn1) {
            AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
            dlg.setTitle("Please confirm your decision.");
            dlg.setMessage("Really?");
            dlg.setCancelable(false);
            //Confirm Buttom
            dlg.setPositiveButton("Confirm",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog,int which) {
                    Toast.makeText(MainActivity.this,"Confirm action",Toast.LENGTH_SHORT).show();
                }
            });
            //Cancel action button
            dlg.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog,int which) {
                    Toast.makeText(MainActivity.this,"Cancel action",Toast.LENGTH_SHORT).show();
                }
            });
            dlg.show();
        }
    }
}

Progress Dialog

点击按钮,显示进程图标,并且设定3秒后自动关闭。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button1"/>

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.progressdialog;

import java.util.TimerTask;
import java.util.Timer;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog dlg = new ProgressDialog(MainActivity.this);
                dlg.setTitle("Program is on the way.");
                dlg.setMessage("Wait for a minutes plz...");
                dlg.setCancelable(false); //Whether dialog be cancelled by other ways or not.
                //
                dlg.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(final DialogInterface dialog) {
                        Timer timer = new Timer();
                        TimerTask task = new TimerTask() {
                            @Override
                            public void run() {
                                dialog.dismiss();
                            }
                        };
                        timer.schedule(task,3000);
                    }
                });
                dlg.show();
            }
        });
    }
}

在 Activity 中使用菜单,需要完成以下工作:

  1. 使用 xml 文件定义菜单
  2. 在 Activity 中关联菜单
  3. 定义各个菜单选项的响应代码

通过创建 MenuDemo 来实现点击右上角弹出菜单,每点击一个选项会显示相应 Toast。

首先在 res 目录添加 menu 目录,并新建 Menu resources file 添加一个 xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menuitem1"
        android:title="Menu1"/>
    <item android:id="@+id/menuitem2"
        android:title="Menu2"/>
    <item android:id="@+id/menuitem3"
        android:title="Menu3"/>
</menu>

MainActivity.java

package com.example.menudemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    //Context menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mi = getMenuInflater();
        mi.inflate(R.menu.mainmenu,menu);
        return true;
    }

    //Response menu item
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.menuitem1:
            {
                Toast.makeText(this,"MenuItem 1",Toast.LENGTH_SHORT).show();
            } break;
            case R.id.menuitem2:
            {
                Toast.makeText(this,"MenuItem 2",Toast.LENGTH_SHORT).show();
            } break;
            case R.id.menuitem3:
            {
                Toast.makeText(this,"MenuItem 3",Toast.LENGTH_SHORT).show();
            } break;
        }
        return true;
    }
}

Radio Button

实现单选组 RadioGroup,并且显示相应 Toast。

activity_main.xml

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

    <TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Sex"/>

    <RadioGroup android:id="@+id/rg_sex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <RadioButton android:id="@+id/sex_0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Secret"
        android:checked="true"/>
    <RadioButton android:id="@+id/sex_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Boy"/>
    <RadioButton android:id="@+id/sex_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Girl"/>
    </RadioGroup>

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1"/>

</LinearLayout>

MainActivity.java

package com.example.radiobuttondemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    RadioGroup rgSex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        rgSex = (RadioGroup)findViewById(R.id.rg_sex);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int rdoId = rgSex.getCheckedRadioButtonId();

//Simplified step
//通过 RadioGroup 对象的 getCheckedRadioButtonId() 方法获取已选中 RadioButton 对象的 ID。然后,通过ID的比较显示相应的内容。
  //   RadioButton rdo = (RadioButton)findViewById(rdoId);
  //   Toast t = Toast.makeText(MainActivity.this, rdo.getText(), Toast.LENGTH_SHORT);
  //   t.show();

                String msg;
                switch (rdoId)
                {
                    case R.id.sex_1:msg="Boy";break;
                    case R.id.sex_2:msg="Girl";break;
                    default:msg="Secret";break;
                }
                Toast t = Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}

其他方法

通过 RadioGroup 的 OnCheckedChangeListener 事件响应选项改变时的操作。
activity_main.xml 不变,更改 MainActivity.java。

package com.example.radiobuttondemo;

import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    RadioGroup rgSex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        rgSex = (RadioGroup)findViewById(R.id.rg_sex);
        //
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group,@IdRes int checkedId) {
                RadioButton rdo = (RadioButton)findViewById(checkedId);
                Toast t = Toast.makeText(MainActivity.this,rdo.getText(),Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}

Check Box Demo

CheckBox 称为复选框,用于定义“开/关”状态。 本 Demo 实现复选框,并显示选中内容的 TextView。

activity_main.xml

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

    <CheckBox android:id="@+id/chk1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Economic"/>

    <CheckBox android:id="@+id/chk2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Car"/>

    <CheckBox android:id="@+id/chk3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Music"/>

    <Button android:id="@+id/btn1"
        android:text="Content of interest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.example.checkboxdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private int[] chkList = {R.id.chk1, R.id.chk2, R.id.chk3};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = "";
                for (int chkId : chkList)
                {
                    CheckBox chk = (CheckBox)findViewById(chkId);
                    if (chk.isChecked()) msg = msg+" "+chk.getText();
                }
                TextView txt1 = (TextView)findViewById(R.id.txt1);
                txt1.setText(msg);
            }
        });
    }
}

选中状态自动响应

package com.example.checkboxdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    private int[] chkList = {R.id.chk1, R.id.chk2, R.id.chk3};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        for (int chkId : chkList) {
            CheckBox chk = (CheckBox)findViewById(chkId);
            chk.setOnCheckedChangeListener(this);
        }
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = "";
                for (int chkId : chkList)
                {
                    CheckBox chk = (CheckBox)findViewById(chkId);
                    if (chk.isChecked()) msg = msg + " " + chk.getText();
                }
                TextView txt1 = (TextView)findViewById(R.id.txt1);
                txt1.setText(msg);
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
    {
        TextView txt1 = (TextView)findViewById(R.id.txt1);
        String msg = buttonView.getText().toString();
        if (isChecked) msg += "Selected";
        else msg += "unSelected";
        txt1.setText(msg);
    }
}

Spinner Demo

创建下拉列表,并设置多个选项,当选中某个选项后单击按钮 Button 1 可以显示相应 Toast。 首先应该更改 app\res\values\strings.xml 文件,在其中创建下拉列表。

strings.xml

<resources>
    <string name="app_name">SpinnerDemo</string>

    <string-array name="cities">
        <item>Bejing</item>
        <item>Shanghai</item>
        <item>Tianjin</item>
        <item>Chongqing</item>
    </string-array>

</resources>

activity_main.xml

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

    <Button android:id="@+id/btn1"
        android:text="Button 1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Plz select city"/>

    <Spinner android:id="@+id/city_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries=" @array/cities ">
    </Spinner>

</LinearLayout>

MainActivity.java

package com.example.spinnerdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private String[] cityNames;
    private Spinner cityList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get city names
        cityNames = getResources().getStringArray(R.array.cities);
        cityList = (Spinner)findViewById(R.id.city_list);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = cityList.getSelectedItemPosition();
                String name = cityNames[index];
                //
                String msg = String.format("%d : %s",index,name);
                Toast t = Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }
}

OnItemSelected

选择城市实现自动处理,需要修改如下。

package com.example.spinnerdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private String[] cityNames;
    private Spinner cityList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get city names
        cityNames = getResources().getStringArray(R.array.cities);
        cityList = (Spinner)findViewById(R.id.city_list);
        //
        cityList.setOnItemSelectedListener(this);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = cityList.getSelectedItemPosition();
                String name = cityNames[index];
                //
                String msg = String.format("%d : %s",index,name);
                Toast t = Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        String msg = String.format("%d : %s",position,cityNames[position]);
        Toast t = Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT);
        t.show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        //Nothing to do
    }
}

Change Mode

改变 Mode 属性为弹出对话框。
仅需在 activity_main.xml 更改下列代码即可:

<Spinner android:id="@+id/city_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries=" @array/cities "
        android:spinnerMode="dialog">
    </Spinner>

Image View Demo

注册图片的单击事件,根据 counter 字段是否为偶数来判断显示的图片,从而实现两张照片的切换。 首先将 round.png 和 robot.png 复制到 app\res\drawable 目录中

activity_main.xml

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

    <ImageView android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/robot"/> //属性设置为图片文件,使用 @drawable 表示

</LinearLayout>

MainActivity.java

package com.example.imageviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    //Counter
    private int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        ImageView img1 = (ImageView)findViewById(R.id.img1);
        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView img = (ImageView)v;
                if (counter %2 == 0)
                    img.setImageResource(R.drawable.round);
                else
                    img.setImageResource(R.drawable.robot);
                counter++;
            }
        });
    }
}

List View Demo

实现列表显示,点击显示响应 Toast。

activity_main.xml

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

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

</LinearLayout>

MainActivity.java

package com.example.listviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    //List data
    private String[] data = {"aaa","bbb","ccc","ddd","eee","fff","ggg","hhh"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initialize list
        ArrayAdapter<String> ada = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);
        //
        ListView lst1 = (ListView)findViewById(R.id.lst1);
        lst1.setAdapter(ada);
        //
        lst1.setOnItemClickListener(this);
    }
        //Click
        @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            if (id>=0) {
                String s = data[(int) id];
                Toast t = Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT);
                t.show();
            }
        }
    }

Progress Bar Demo

实现点击按钮显示条形进度条,并10秒后结束。

activity_main.xml

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

    <ProgressBar android:id="@+id/pd1"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1"/>

</LinearLayout>

MainActivity.java

package com.example.progressbardemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import java.util.Timer;
import java.util.TimerTask;

import static android.R.style.Widget;

public class MainActivity extends AppCompatActivity {

    ProgressBar pd1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Progress Bar
        pd1 = (ProgressBar)findViewById(R.id.pd1);
        pd1.setProgress(0);
        //
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pd1.setProgress(0);
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        int cur = pd1.getProgress();
                        cur += 10;
                        if (cur <= 100) {
                            pd1.setProgress(cur);
                        } else {
                            this.cancel();
                        }
                    }
                };
                timer.scheduleAtFixedRate(task,0,1000);
            }
        });

    }
}
Top
Foot