歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android2.2以上使用HorizontalScrollView取代Gallery

Android2.2以上使用HorizontalScrollView取代Gallery

日期:2017/3/1 9:58:26   编辑:Linux編程

近期一直在做我的畢業設計--鄭大學生助手,先給這個Android應用做一個主題切換功能,以前也使用過Gallery,最初自己的想法也是使用這個,再讓用戶選擇使用哪一個,可是當我在寫代碼中,eclipse提示The type Gallery is deprecated。查閱資料後發現2.2以上版本已經用HorizontalScrollView取代Gallery ,原因Gallery每次切換圖片時都要新建視圖,造成太多的資源浪費。

我現在需要的是在手機上顯示可以滑動的幾張圖片,也就是各個主題對應的圖片,然後用戶點擊圖片進行切換就行了,使用Gallery需要設置相應的適配器,但是使用HorizontalScrollView卻顯得非常的簡單。

具體代碼如下:

1 創建xml:

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:saveEnabled="false"
android:scrollbars="none" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >

<ImageView
android:id="@+id/theme1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/theme1" >
</ImageView>

<ImageView
android:id="@+id/theme2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/theme2" >
</ImageView>
</LinearLayout>

</HorizontalScrollView>

2 控制代碼

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class GalleryTest extends Activity implements OnClickListener{

private ImageView theme1,theme2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.gallery);

theme1=(ImageView)findViewById(R.id.theme1);
theme2=(ImageView)findViewById(R.id.theme2);
theme1.setOnClickListener(this);
theme2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==theme1){
Toast.makeText(this, "主題1", Toast.LENGTH_SHORT).show();
//真正的主題切換
}else if(v==theme2){
Toast.makeText(this, "主題2", Toast.LENGTH_SHORT).show();
//真正的主題切換
}

}

}

這樣就可以,效果圖如下(僅僅演示而已):

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved