安卓高階介面設計
安卓高階介面設計
1、自動完成文字框
自動完成文字框(AutoCompleteTextView),用於實現允許使用者輸入一定字元後,顯示一個下拉選單,供使用者從中選擇,當用戶選擇某個選項後,按使用者選擇自動填寫該文字框。
AutoCompleteTextView元件繼承自EditText,.所以它支援EditText元件提供的屬性
<?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" > <AutoCompleteTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/autoComplete" android:text="" android:completionThreshold="2" android:completionHint="輸入搜尋內容" android:layout_weight="7"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="搜尋" android:id="@+id/button" android:layout_weight="1" android:layout_marginLeft="10px"/> </LinearLayout>
package com.example.autocompletetextviewproject; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static final String[] COUNTRIES = new String[]{"android", "android app", "android framework", "研發工程師", "產品經理"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, COUNTRIES); autoCompleteTextView.setAdapter(arrayAdapter); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show(); } }); } }
2、進度條
當一個應用在後臺執行時,前臺介面不會有任何資訊,這時使用者根本不知道程式是否在執行以及熱行進度等,因此需要使用進度條來提示程式執行的進度。在Android中,進度條(ProgressBar)用於向用戶顯示某個耗時操作完成的百分比。
setProgress(int progress))方法:用於設定進度完成的百分比。
incrementProgressBy(int diff)方法:用於設定進度條的進度增加或減少。當引數值為正數時,表示進度增加;為負數時,表示進度減少。
實現圓形進度條和水平進度條
<?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"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:id="@+id/progress1"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progress2"
style="?android:attr/progressBarStyleLarge"
/>
</LinearLayout>
package com.example.progressbarproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ProgressBar hori;
private ProgressBar cori;
private int setProgress = 0;
private Handler mhandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hori = (ProgressBar) findViewById(R.id.progress1);
cori = (ProgressBar) findViewById(R.id.progress2);
mhandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0x111){
hori.setProgress(setProgress);
}else {
Toast.makeText(MainActivity.this, "進度已完成", Toast.LENGTH_SHORT).show();
hori.setVisibility(View.GONE);
cori.setVisibility(View.GONE);
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
while (true){
setProgress = doWork();
Message message = new Message();
if (setProgress < 100){
message.what = 0x111;
mhandler.sendMessage(message);
}else {
message.what = 0x110;
mhandler.sendMessage(message);
break;
}
}
}
public int doWork(){
setProgress += Math.random()*10;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
return setProgress;
}
}
}).start();
}
}
3、拖動條和星級評分條
在Andriod中,提供了兩種允許使用者通過拖動來改變進度的元件,分別是拖動條(Seek Bar)和星級評分條(RatmgBar),下面分別進行介紹。
3.1、拖動條
拖動條與進度條類似,所不同的是,拖動條允許使用者拖動滑塊來改變值,通常用於實現對某種數值的調節。例如,調節圖片的透明度或是音量等。
<?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"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="當前值:50"
android:id="@+id/text"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:max="100"
android:progress="50"
android:padding="20px"/>
</LinearLayout>
package com.example.seekbarproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
final TextView textView = (TextView) findViewById(R.id.text);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
Toast.makeText(MainActivity.this, "結束滑動", Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this, "開始滑動", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
textView.setText("當前值:" + seekBar.getProgress());
}
});
}
}
3.2、星級評分條
星級評分條與拖動條類似,都允許使用者拖動來改變進度,所不同的是,星級評分條通過星星圖案表示進度。通常情況下,使用星級評分條表示對某一事物的支援度或對某種服務的滿意程度等。例如,淘寶網中對賣家的好評度,就是通過星級評分條實現的。
getRating():用於獲取等級,表示選中了幾顆星。
getStepSize():用於獲取每次最少要改變多少個星級。
getProgress()方法:用於獲取進度,獲取到的進度值為getRatingO方法返回值與getStepSizeO方法返回值之積。
<?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"
android:orientation="vertical">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratinBar"
android:numStars="5"
android:rating="3.5"
android:isIndicator="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交"
android:id="@+id/button"/>
</LinearLayout>
package com.example.ratinbarproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
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);
RatingBar ratingBar = (RatingBar) findViewById(R.id.ratinBar);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float rating = ratingBar.getRating();
int progress = ratingBar.getProgress();
int numStars = ratingBar.getNumStars();
Toast.makeText(MainActivity.this, (int) (rating + progress + numStars), Toast.LENGTH_SHORT).show();
}
});
}
}
4、選項卡
選項卡主要由TabHost、.TabWidget和FrameLayout3個元件組成,用於實現一個多標籤頁的使用者介面,通過它可以將一個複雜的對話方塊分割成若干個標籤頁,實現對資訊的分類顯示和管理。使用該元件不僅可以使介面簡潔大方,還可以有效地減少窗體的個數。
在Android中,實現選項卡的一般步驟如下:
- 在佈局檔案中新增實現選項卡所需的TabHost、Tab Widget和FrameLayout:元件,
- 編寫各標籤頁中要顯示內容所對應的XL佈局檔案。
- 在Activity中,獲取並初始化TabHost元件
- 為TabHost物件新增標籤頁。
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/tabhost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/tabs"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/tabcontent"/>
</LinearLayout>
</TabHost>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tab1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="豐富多彩的智慧世界"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="讓我們的智慧技術應用於每一臺裝置"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tab2"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="豐富多彩的智慧世界"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="讓我們的智慧技術應用於每一臺裝置"/>
</LinearLayout>
package com.example.tablehostproject;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
private TabHost tabHost;
@SuppressLint("ResourceType")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
LayoutInflater layoutInflater = LayoutInflater.from(this);
layoutInflater.inflate(R.id.tab1, tabHost.getTabContentView());
layoutInflater.inflate(R.id.tab2, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("11111").setContent(R.id.tab1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("22222").setContent(R.id.tab2));
}
}
5、影象切換器
影象切換器(ImageSwitcher),用於實現類似於Windows作業系統下的"Windows照片檢視器"中的上一張、下一張切換圖片的功能。在使用ImageSwitcher時,必須實現ViewSwitcher..ViewFactory介面,並通過makeView()方法來建立用於顯示圖片的ImageView.make View()方法將返回一個顯示圖片的ImageView。在使用影象切換器時,還有一個方法非常重要,那就是setImageResource(方法,該方法用於指定要在ImageSwitcher中顯示的圖片資源
<?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"
android:orientation="vertical"
android:gravity="center"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一張"
android:id="@+id/button1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一張"
android:id="@+id/button2"/>
<ImageSwitcher
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageswitcher"/>
</LinearLayout>
package com.example.imageswichterproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class MainActivity extends AppCompatActivity {
private int[] imaid = new int[]{R.drawable.icon01, R.drawable.icon02, R.drawable.icon03,
R.drawable.icon04, R.drawable.icon05, R.drawable.icon06};
private int index = 0;
private ImageSwitcher imageSwitcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return imageView;
}
});
imageSwitcher.setImageResource(imaid[index]);
Button dawn = (Button) findViewById(R.id.button1);
Button up = (Button) findViewById(R.id.button2);
dawn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (index < imaid.length - 1){
index++;
}else {
index = 0;
}
imageSwitcher.setImageResource(imaid[index]);
}
});
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (index > 0){
index--;
}else {
index = imaid.length - 1;
}
imageSwitcher.setImageResource(imaid[index]);
}
});
}
}
6、網格檢視
網格檢視(GridView)是按照行、列分佈的方式來顯示多個元件,通常用於顯示圖片或是圖示等。在使用網格檢視時,首先需要在螢幕上新增GridView元件,通常使用
GridView與ListView類似,都需要通過Adapter來提供要顯示的資料。在使用GridView元件時,通常使用SimpleAdapter或者BaseAdapter類為GridView元件提供資料。下面通過一個具體的例項演示如何通過SimpleAdapter介面卡指定內容的方式建立GridView。
<?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"
>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:stretchMode="columnWidth"
android:id="@+id/gridV"/>
</LinearLayout>
<?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"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image1"
android:scaleType="fitCenter"
android:paddingLeft="10px"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px"
android:layout_gravity="center"
android:id="@+id/text"/>
</LinearLayout>
package com.example.gridviewproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private int[] imageid = new int[]{R.drawable.icon03, R.drawable.icon03, R.drawable.icon03,
R.drawable.icon03, R.drawable.icon03, R.drawable.icon03, R.drawable.icon03,
R.drawable.icon03, R.drawable.icon03, R.drawable.icon03, R.drawable.icon03,
R.drawable.icon03};
private String[] strings = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < imageid.length; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageid[i]);
map.put("title", strings[i]);
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.item, new String[]{"image", "title"}, new int[]{R.id.image1, R.id.text});
GridView gridView = (GridView) findViewById(R.id.gridV);
gridView.setAdapter(adapter);
}
}
如果只想在GridView中顯示照片而不顯示說明性文字,可以使用BaseAdapter基本介面卡為其指定內容。使用BaseAdapter為GridView元件設定內容可以分為以下兩個步驟。
建立BaseAdapter類的物件,並重寫其中的getView(、getItemId(、getItem(和getCountO方法,其中最主要的是重寫getView()方法來設定顯示圖片的格式。以例2.7為例,將該例項中的GridView元件修改為使用BaseAdapter類設定內容的程式碼如下:
BaseAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return imageid.length;
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView imageView;
if (view == null){
imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setPadding(5, 0, 5, 0);
}else {
imageView = (ImageView) view;
}
imageView.setImageResource(imageid[i]);
return imageView;
}
};
GridView gridView = (GridView) findViewById(R.id.gridV);
gridView.setAdapter(adapter);
7、畫廊檢視
畫廊檢視(Gallery)表示,能夠按水平方向顯示內容,並且可用手指直接拖動圖片移動,一般用來瀏覽圖片,被選中的選項位於中間,並且可以響應事件顯示資訊。在使用畫廊檢視時,首先需要在螢幕上新增Gallery元件,通常使用
使用畫廊檢視,也需要使用Adapter提供要顯示的資料。通常使用BaseAdapter類為Gallery元件提供資料。
下面通過一個具體的例項演示通過BaseAdapter介面卡為Gallery元件提供要顯示的圖片。
<?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"
>
<Gallery
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spacing="5px"
android:unselectedAlpha="0.6"
android:id="@+id/gallery"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground"/>
</declare-styleable>
</resources>
package com.example.galleryproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private int[] imageid = new int[]{R.drawable.icon03, R.drawable.icon03, R.drawable.icon03,
R.drawable.icon03, R.drawable.icon03, R.drawable.icon03, R.drawable.icon03,
R.drawable.icon03, R.drawable.icon03, R.drawable.icon03, R.drawable.icon03};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
BaseAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return imageid.length;
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView imageView;
if (view == null){
imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(300, 300));
TypedArray attributes = obtainStyledAttributes(R.styleable.Gallery);
imageView.setBackgroundResource(attributes.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
imageView.setPadding(5, 0, 5, 0);
}else {
imageView = (ImageView) view;
}
imageView.setImageResource(imageid[i]);
return imageView;
}
};
gallery.setAdapter(adapter);
gallery.setSelection(imageid.length/2);
gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
"你點選了第" + String.valueOf(i + 1) + "張圖片", Toast.LENGTH_SHORT).show();
}
});
}
}
8、範例
幻燈片式圖片瀏覽器
<?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"
android:gravity="center"
android:orientation="vertical">
<ImageSwitcher
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="30px"
android:layout_weight="2"
android:id="@+id/imageS"/>
<Gallery
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/gallery"
android:spacing="5px"
android:unselectedAlpha="0.6"
android:layout_weight="1"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground"/>
</declare-styleable>
</resources>
package com.example.fanli_project;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class MainActivity extends AppCompatActivity {
private int[] imageId = new int[]{R.drawable.icon03, R.drawable.icon05, R.drawable.icon03,
R.drawable.icon05, R.drawable.icon03, R.drawable.icon05};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageS);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
imageSwitcher.setOutAnimation(this, android.R.anim.fade_out);
imageSwitcher.setInAnimation(this, android.R.anim.fade_in);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return imageView;
}
});
BaseAdapter baseAdapter = new BaseAdapter() {
@Override
public int getCount() {
return imageId.length;
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView imageView;
if (view == null){
imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(300, 300));
TypedArray attributes = obtainStyledAttributes(R.styleable.Gallery);
imageView.setBackgroundResource(attributes.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
imageView.setPadding(5, 0, 5, 0);
}else {
imageView = (ImageView) view;
}
imageView.setImageResource(imageId[i]);
return imageView;
}
};
gallery.setAdapter(baseAdapter);
gallery.setSelection(imageId.length/2);
gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
imageSwitcher.setImageResource(imageId[i]);
}
});
}
}
訊息提示框與對話方塊
1、使用Toast顯示訊息提示框
建立一個Toast物件。通常有兩種方法:一種是使用構造方式進行建立;另一種是呼叫Toast類的makeText()方法建立。
構造方法:
Toast toast = new Toast(this);
makeText()方法:
Toast toast = Toast.makeText(this, "要顯示的內容", Toast.LENGTH_SHORT);
2、使用Notification在狀態列顯示通知
Android8及其之後,使用Notification的步驟:
(1)呼叫getSystemService()方法獲取系統的NotificationManager服務
(2)建立通知構造器NotificationCompat.Builder物件。
(3)呼叫NotificationCompat.Builder物件的方法設定通知相關內容。
(4)通過notify()方法傳送Notification通知。
通過一個具體的例項說明如何使用Notification在Android8版本的狀態列上顯示通知。
<?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"
android:orientation="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button01"
android:text="傳送通知"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button02"
android:text="消除通知"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="詳細內容"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.notificationfanliproject;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send = (Button) findViewById(R.id.button01);
Button clear = (Button) findViewById(R.id.button02);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "channel_1";//設定通道id屬性
String description = "123";//設定通道描述
int importance = NotificationManager.IMPORTANCE_HIGH;//重要通知聲音提醒
int NOTIFYID_1 = 0x1;
//int NOTIFYID_2 = 0x2;
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NotificationChannel notificationChannel = new NotificationChannel(id, "123", importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
Intent intent = new Intent(MainActivity.this, ContextActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this, id)
.setContentTitle("這是通知的標題")
.setSmallIcon(R.drawable.icon09)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon09))
.setContentText("這是通知內容")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(NOTIFYID_1, notification);
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notificationManager.cancelAll();
}
});
}
}
package com.example.notificationfanliproject;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
public class ContextActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.context_activity);
}
}
3、使用AlertDialog建立對話方塊
AlertDialog類的功能非常強大,它不僅可以生成帶按鈕的提示對話方塊,還可以生成帶列表的列表對話方塊,概括起來有以下4種:
- 帶確定、中立和取消等N個按鈕的提示對話方塊,其中的按鈕個數不是固定的,可以根據需要新增。例如,不需要中立按鈕,則可以生成只帶有確定和取消按鈕的對話方塊,也可以是隻帶有一個按鈕的對話方塊。
- 帶列表的列表對話方塊。
- 帶多個單選列表項和N個按鈕的列表對話方塊。
- 帶多個多選列表項和N個按鈕的列表對話方塊。
通常情況下,使用AlertDialog類只能生成帶N個按鈕的提示對話方塊,要生成另外3種列表對話方塊,需要使用AlertDialog.Builder類,AlertDialog.Builder類提供的常用方法如表所示。
下面通過一個具體的例項說明如何應用AlertDialog類生成提示對話方塊和各種列表對話方塊。
<?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"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕1"
android:id="@+id/button1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕2"
android:id="@+id/button2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕3"
android:id="@+id/button3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕4"
android:id="@+id/button4"/>
</LinearLayout>
package com.example.dialogproject;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private boolean[] checkedItems;
private String[] items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setIcon(R.drawable.icon10);
alertDialog.setTitle("系統提示");
alertDialog.setMessage("帶取消、確定、中立的對話方塊");
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你點選了取消按鈕", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你點選了確認按鈕", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "中立", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你點選了中立按鈕", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] str = new String[]{"語文", "數學", "物理", "化學", "英語"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.icon10);
builder.setTitle("選擇你喜歡的科目");
builder.setItems(str, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你選擇了"+str[i], Toast.LENGTH_SHORT).show();
}
});
builder.create().show();
}
});
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] str = new String[]{"語文", "數學", "物理", "化學", "英語"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.icon10);
builder.setTitle("選擇你喜歡的科目");
builder.setSingleChoiceItems(str, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你選擇了" + str[i], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("確定", null);
builder.create().show();
}
});
Button button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkedItems = new boolean[]{false, true, false, true, false};
items = new String[]{"語文", "數學", "物理", "化學", "英語"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("選擇你喜歡的學科");
builder.setIcon(R.drawable.icon10);
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
checkedItems[i] = b;
}
});
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String result = "";
for (int j = 0; j < checkedItems.length; j++) {
if (checkedItems[j]){
result += items[j] + "、";
}
}
if (!"".equals(result)){
result = result.substring(0, result.length() - 1);
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
});
builder.create().show();
}
});
}
}