Android入门

快速上手

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.zypc.javaandroiddemo;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button); //按钮ID为"button"
EditText editTextText=(EditText)findViewById(R.id.editTextText); //输入框ID为"editTextText"
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String gotText=editTextText.getText().toString();
if(gotText.equals("aaa")){
Toast toast=Toast.makeText(MainActivity.this,"Flag正确!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER,0,0);
toast.show();
}
}
});
}
}

布局基础

XML控制UI界面

在res/layout目录下新建XML布局文件,例如“main_activity.xml”,在Java中这样导入:

1
setContentView(R.layout.activity_main);

在布局文件中:

1
2
3
4
5
6
7
8
9
10
11
<FrameLayout ...
...
android:background="@mipmap/bg"
...
<TextView
...
android:layout_gravity="center"
android:text="@string/start"
android:textSize="18sp"
android:textColor="#115572" />
</FrameLayout>

再在res/values下的strings.xml中添加字符串常量:

1
2
3
4
5
<?xml ...?>
<resources>
<string name="app_name">桌面台球</string>
<string name="start">开始游戏</string>
</resources>

Java控制UI界面

手动用Java新建文本“开始游戏”,点击后出现系统原生提示框,确定进入,退出直接结束程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.noname.myapplication;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public TextView text1;

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

FrameLayout frameLayout=new FrameLayout(this); //创建帧布局管理器
setContentView(frameLayout); //在Activity中显示frameLayout

text1=new TextView(this);
text1.setText("开始游戏");
text1.setTextSize(TypedValue.COMPLEX_UNIT_SP,18); //可缩放像素18 固定像素为PX
text1.setTextColor(Color.rgb(17,85,114)); //文字颜色

FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); //创建保存布局参数的对象
params.gravity= Gravity.CENTER; //居中显示
text1.setLayoutParams(params); //设置布局参数

text1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
new AlertDialog.Builder(MainActivity.this)
.setTitle("系统提示")
.setMessage("游戏有风险,进入需谨慎,真的要进入吗?")

.setPositiveButton("确定",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Log.i("桌面台球","进入游戏");
}
})

.setNegativeButton("退出",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog,int which){
Log.i("桌面台球","退出游戏"); //消息日志
finish(); //退出程序
}
})
.show();
}
});
frameLayout.addView(text1);//添加到布局管理器中
}
}

XML与Java混合控制UI界面

做一个3行4列的相册照片列表页面。

1
2
3
4
5
6
7
8
9
<?xml ... ?>
<GridLayout ...
xxx
android:id="@+id/layout"
...
android.orientation="horizontal"
android.rowCount="3"
android.columnCount="4"
</GridLayout>

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

private ImageView[] img=new ImageView[12];
private int[] imagePath=new int[]{
R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,R.mipmap.img04,
R.mipmap.img05,R.mipmap.img06,R.mipmap.img07,R.mipmap.img08,
R.mipmap.img09,R.mipmap.img10,R.mipmap.img11,R.mipmap.img12
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GridLayout layout=(GridLayout)findViewById(R.id.layout);
for(int i=0;i<imagePath.length;i++){
img[i]=new ImageView(MainActivity.this);
img[i].setImageResource(imagePath[i]);
img[i].setPadding(2,2,2,2);
ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(116,68);
img[i].setLayoutParams(params);
layout.addView(img[i]);
}
}
}

自定义View

跟随手指的小兔子。

XML布局:

1
2
3
4
5
6
<FrameLayout ...
...
android:backgroud="@mipmap/background"
android:id="@+id/mylayout"
...>
</FrameLayout>

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

public class RabbitView extends View {
public float bitmapX;
public float bitmapY;
public RabbitView(Context context){
super(context);
bitmapX=290; //默认位置
bitmapY=130;
}

@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint paint=new Paint(); //创建并实例化绘制对象
Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(),R.mipmap.rabbit); //生成位图对象
canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint); //绘制小兔子
if(bitmap.isRecycled()){ //图片是否回收
bitmap.recycle(); //强制回收
}
}
}
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout=(FrameLayout)findViewById(R.id.mylayout);
final RabbitView rabbit=new RabbitView(this);
rabbit.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){
rabbit.bitmapX=event.getX();
rabbit.bitmapY=event.getY();
rabbit.invalidate(); //重绘rabbit组件
return true;
}
});
frameLayout.addView(rabbit); //添加到布局管理器
}
}

布局管理器

相对布局

XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<RelativeLayout ...
...
android:background="@mipmap/bg"
...>
<TextView
android:text="发现有Widget的新版本,您想现在就安装吗?"
android:id="@+id/textView1"
...
android:layout_centerInParent="true"
/>
<Button
android:text="以后再说"
android:id="@_id/button2"
...
android:layout_alignRight="@id/textView1"
android:layout_below="@id/textView1"
/>
<Button
android:text="现在更新"
android:id="@+id/button1"
...
android:layout_below="@id/textView1"
android:layout_toLeftOf="@id/button2"
/>
</RelativeLayout>

线性布局

类似微信登陆界面,XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<LinearLayout ...
...
android:orientation="vertical"
...>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:hint="QQ号/微信号/Email"
android:drawableLeft="@mipmap/zhanghao"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:hint="密码"
android:drawableLeft="@mipmap/mima"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
android:textColor="#FFFFFF"
android:background="#FF009688"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录遇到问题?"
android:gravity="center_horizontal"
android:paddingTop="20dp"
/>
</LinearLayout>

在AndroidMenifest.xml中application标签修改:

1
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"

帧布局

前景图像在右下角,层叠三层正方形,最下层蓝色,然后天蓝色和水蓝色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<FrameLayout
...
android:foreground="@mipmap/mr"
android:foregroundGravity="bottom|right"
...
<TextView
android:id="@_id/textView1"
android:layout_width="280dp"
android:layout_height="280dp"
android:layout_gravity="center"
android:background="#FF0000FF"
android:textColor="#FFFFFF"
android:text="蓝色背景的TextView"
/>
<TextView
android:id="@_id/textView2"
android:layout_width="230dp"
android:layout_height="230dp"
android:layout_gravity="center"
android:background="#FF0077FF"
android:textColor="#FFFFFF"
android:text="天蓝色背景的TextView"
/>
<TextView
android:id="@_id/textView3"
android:layout_width="180dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:background="#FF00B4FF"
android:textColor="#FFFFFF"
android:text="水蓝色背景的TextView"
/>
</FrameLayout>

表格布局

从线性布局继承来的,该有的都有。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<TableLayout
...
android:background="@mipmap/biaoge"
android:stretchColumns="0,3"
...><!--第1列和第4列允许被拉伸-->
<!--第一行-->
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="200dp"
>
<TextView/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="账号:"
android:gravity="center_horizontal"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="邮箱或者手机号"
/>
<TextView/>
</TableRow>
<!--第二行-->
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="200dp"
>
...
</TableRow>
...
</TableLayout>

网格布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<GridLayout
...
android:background="@mipmap/bg"
android:columnCount="6"
...><!--共6列-->
<ImageView
...
android:layout_gravity="end"
android:layout_columnSpan="4"
android:layout_column="1"
android:layout_row="0"
...
/><!--放置在结束位置、占4列、从第2列第1行开始-->
...
</GridLayout>

常用UI组件

TextView

略。

EditText

1
2
EditText login=(EditText)findViewById(R.id.login);
String loginText=login.getText().toString();

Button

1
2
3
4
5
6
7
Button login=(Button)findViewById(R.id.login);
login.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
//...
}
})

ImageButton

Java同Button,XML加上:

1
2
3
4
5
<ImageButton
...
android:src="@mipmap/play"
>
</ImageButton>

RadioGroup

RadioGroup组件中有若干个RadioButton。

选项改变就触发方法:

1
2
3
4
5
6
7
8
RadioGroup sex=(RadioGroup)findViewById(R.id.radioGroup1);
sex.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group,int checkedId){
RadioButton r=(RadioButton)findViewById(checkedId);
r.getText(); //获取选中选项的文本
}
});

选项改变后单击其他元素按钮触发方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final RadioGroup sex=(RadioGroup)findViewById(R.id.radioGroup1);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
for(int i=0;i<sex.getChildCount();i++){
RadioButton r=(RadioButton)sex.getChildAt(i);
if(r.isChecked()){
r.getText();
break;
}
}
}
});

CheckBox

1
2
3
4
5
6
7
8
9
final CheckBox like1=(CheckBox)findViewById(R.id.like1);
like1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){
if(like1.isChecked()){
like1.getText();
}
}
});

DatePicker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

int year,month,day;
DatePicker datePicker;

private void show(int year,int monthOfYear,int dayOfMonth){
String str=year+"年"+monthOfYear+1+"月"+dayOfMonth+"日";
Toast.makeText(MainActivity.this,str, Toast.LENGTH_SHORT).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datePicker=(DatePicker)findViewById(R.id.datePicker);
Calendar calendar=Calendar.getInstance();
year=calendar.get(Calendar.YEAR);
month=calendar.get(Calendar.MONTH);
day=calendar.get(Calendar.DAY_OF_MONTH);
datePicker.init(year,month,day,new DatePicker.OnDateChangedListener(){//获取到的是0~11月,需要+1
@Override
public void onDateChanged(DatePicker arg0,int year,int month,int day){
MainActivity.this.year=year;
MainActivity.this.month=month;
MainActivity.this.day=day;
show(year,month,day);
}
});
}
}

TimePicker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

int hour,minute;
TimePicker timePicker;

private void show(int hourOfDay,int minute){
String str=hourOfDay+"时"+minute+"分";
Toast.makeText(MainActivity.this,str, Toast.LENGTH_SHORT).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
timePicker=(TimePicker)findViewById(R.id.timePicker);
Calendar calendar=Calendar.getInstance();
hour=calendar.get(Calendar.HOUR_OF_DAY);
minute=calendar.get(Calendar.MINUTE);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener(){
@Override
public void onTimeChanged(TimePicker view,int hourOfDay,int minute){
MainActivity.this.hour=hourOfDay;
MainActivity.this.minute=minute;
show(hourOfDay,minute);
}
});
}
}

Chronometer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.WindowManager;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {

Chronometer ch;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //设置全屏

ch=(Chronometer)findViewById(R.id.ch);
ch.setBase(SystemClock.elapsedRealtime()); //记录起始时间
ch.setFormat("%s"); //显示时间格式
ch.start(); //开启计时器
ch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener(){
@Override
public void onChronometerTick(Chronometer chronometer){
if(SystemClock.elapsedRealtime()-ch.getBase()>=60000){
ch.stop();
}
}
});
}
}

ProgressBar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private ProgressBar horizonP;
private int mProgressStatus=0;
private Handler mHandler; //android.os里的

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

horizonP=(ProgressBar)findViewById(R.id.progressBar1);
mHandler=new Handler(){
@Override
public void handleMessage(Message msg){
if(msg.what==0x111){
horizonP.setProgress(mProgressStatus);
}
else{
Toast.makeText(MainActivity.this,"耗时操作已经完成",Toast.LENGTH_SHORT).show();
horizonP.setVisibility(View.GONE); //进度条消失
}
}
};

new Thread(new Runnable(){
public void run(){
while(true){
mProgressStatus=doWork();
Message m=new Message();
if(mProgressStatus<100){
m.what=0x111;
mHandler.sendMessage(m);
}
else{
m.what=0x110;
mHandler.sendMessage(m);
break;
}
}
}
private int doWork(){//模拟耗时操作
mProgressStatus+=Math.random()*10;
try{
Thread.sleep(200);
}
catch(InterruptedException e){
e.printStackTrace();
}
return mProgressStatus;
}
}).start();
}
}

SeekBar

拖动条。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {

private ImageView image;
private SeekBar seekBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

image=(ImageView)findViewById(R.id.image);
seekBar=(SeekBar)findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar arg0,int progress,boolean fromUser){
image.setImageAlpha(progress); //图像透明度
}

@Override
public void onStartTrackingTouch(SeekBar bar){

}
@Override
public void onStopTrackingTouch(SeekBar bar){

}
});
}
}

RatingBar

星级评分条。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;

public class MainActivity extends AppCompatActivity {

private RatingBar ratingbar;

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

ratingbar=(RatingBar)findViewById(R.id.ratingBar1);
Button button=(Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
int result=ratingbar.getProgress();
float rating=ratingbar.getRating();
float step=ratingbar.getStepSize();
Toast.makeText(MainActivity.this,"你得到了"+rating+"颗星",Toast.LENGTH_SHORT).show();
}
});
}
}

ImageView

原始尺寸:

1
2
3
4
5
6
7
8
9
10
<ImageView
android:src="@mipmap/flower"
android:id="@+id/imageView2"
android:maxWidth="90dp"
android:maxHeight="90dp"
android:adjustViewBounds="true"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>

限制高度和宽度:

1
2
3
4
5
<ImageView
...
android:adjustViewBound="true"
...
/>

保持纵横比缩放图片,并完全显示在ImageView组件右下角:

1
2
3
4
5
<ImageView
...
android:scaleType="fitEnd"
...
/>

图像着色为半透明红色:

1
2
3
4
5
<ImageView
...
android:tint="#77FF0000"
...
/>

修改AndroidManifest.xml:

1
2
3
4
<activity 
android:name=".MainActivity"
android:screenOrientation="landscape"
>

ImageSwitcher

图像切换器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class MainActivity extends AppCompatActivity {

private int[] arrayPictures=new int[]{
R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,
R.mipmap.img07,R.mipmap.img08,R.mipmap.img09
};
private ImageSwitcher imageSwitcher;
private int pictutureIndex;
private float touchDownX; //左右滑动时手指按下的X坐标
private float touchUpX; //抬起的X坐标

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

imageSwitcher=(ImageSwitcher)findViewById(R.id.imageswitcher);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory(){ //用Factory方法为ImageSwitcher制造ImageView
@Override
public View makeView(){
ImageView imageView=new ImageView(MainActivity.this);
imageView.setImageResource(arrayPictures[pictutureIndex]);
return imageView;
}
});

imageSwitcher.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){
if(event.getAction()==MotionEvent.ACTION_DOWN){
touchDownX=event.getX();
return true;
}
else if(event.getAction()==MotionEvent.ACTION_UP){
touchUpX=event.getX();
return true;
}
return false;
}
});

if(touchUpX-touchDownX>100){
pictutureIndex=pictutureIndex==0?arrayPictures.length-1:pictutureIndex-1;
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_right));
imageSwitcher.setImageResource(arrayPictures[pictutureIndex]);
}
}
}

Spinner

下拉列表框。

1
2
3
4
5
<Spinner
android:id="@+id/spinner"
android:entries="@array/ctype"
..>
</Spinner>

在res\values\arrays.xml中:

1
2
3
4
5
6
7
8
<?xml ...?>
<resources>
<string-array name="ctype">
<item>全部</item>
<item>电影</item>
...
</string-array>
</resources>

修改AndroidManifest.xml中的application标签:

1
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

Spinner spinner=(Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onTiemSelected(AdapterView<?>parent, View view, int position, long id){
String result=parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?>parent){

}
});
}
}

另一种用适配器指定要显示的列表项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity {

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

String[] ctype=new String[]{"全部","电影",/*...*/};
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner=(Spinner)findViewById(R.id.spinner1);
spinner.setAdapter(adapter);

spinner.getSelectedItem();//获取选中值的方法
}
}

ListView

实现类似微信通讯录朋友列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.noname.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

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

ListView listview=(ListView)findViewById(R.id.listview);
int[] imageId=new int[]{
R.mipmap.img0, R.mipmap.img1, R.mipmap.img2,
R.mipmap.img3, R.mipmap.img4, R.mipmap.img5,
R.mipmap.img6, R.mipmap.img7, R.mipmap.img8
};
String[] title=new String[]{"刘一","陈二",/*...*/};

List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();
for(int i=0;i<imageId.length;i++){
Map<String,Object>map=new HashMap<String,Object>();
map.put("image",imageId[i]);
map.put("名字",title[i]);
listItems.add(map);
}

SimpleAdapter adapter=new SimpleAdapter(this,listItems,R.layout.main,new String[]{"名字","image"},new int[]{R.id.title,R.id.image});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id){
Map<String,Object>map=(Map<String,Object>)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this,map.get("名字").toString(),Toast.LENGTH_SHORT).show();
}
});
}
}