标签:
17. Gallery 与 衍生BaseAdapter 容器
Gallery控件,即Android的图片库控件。
需要定义一个BaseAdaper的子类(eg.ImageAdapter)来操作控制图片资源,然后在主类中通过Gallery.setAdapter(new ImageAdapter(this));来使用这个控制类。
示例代码
本例中 ImageView 和 Gallery 控件相互协作 .
① 新建项目
② 定义layout 外部resource 的xml 文件,用来改变layout 的背景
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery" >
        <attr name="android:galleryItemBackground" />
        <!-- 定义layout 外部resource 的xml 文件,用来改变layout 的背景图。-->
</declare-styleable>
</resources>
③ 修改main.xml 布局,添加一个Gallery 和一个ImageView
<AbsoluteLayout ...>
<Gallery
    android:layout_width="fill_parent"
    android:layout_height="143px"
    android:layout_x="0px"
    android:layout_y="51px"
    android:id="@+id/Gallery_preView" 
android:unselectedAlpha 设置选中的图片的透明度
android:spacing setSpacing(int) 图片之间的空白大小
android:animationDuration setAnimationDuration (int )
设置布局变化时动画的转换所需的时间(毫秒级)。仅在动画开始时计时。该值必须是整数,比如:100。
>
</Gallery>
<ImageView
    android:layout_width="239px"
    android:layout_height="218px"
    android:layout_x="38px"
    android:layout_y="184px"
    android:id="@+id/ImageView_photo" >
</ImageView>
</AbsoluteLayout>
④ 新建一个myImageAdapter 类--Gallery 的适配器,它继承于BaseAdapter 类.
package zyf.Ex_Ctrl_10ME;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class myImageAdapter extends BaseAdapter {
     @Override
     public int getCount() {
          // TODO Auto-generated method stub
          return 0;
     }
     @Override
     public Object getItem(int position) {
          // TODO Auto-generated method stub
          return null;
     }
     @Override
     public long getItemId(int position) {
          // TODO Auto-generated method stub
          return 0;
     }
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
          // TODO Auto-generated method stub
          return null;
     }
}
⑤ 修改mainActivity.java,添加Gallery 相关操作
package zyf.Ex_Ctrl_10ME;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class Ex_Ctrl_10ME extends Activity {
    // Called when the activity is first created.
    //定义要使用的对象
    private Gallery gallery;
    private ImageView imageview;
    private myImageAdapter imageadapter;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageadapter=new myImageAdapter(this);
        //通过findViewById 取得资源对象
        gallery=(Gallery)findViewById(R.id.Gallery_preView);
        imageview=(ImageView)findViewById(R.id.ImageView_photo);
        //给Gallery设置适配器把Ex_Ctrl_10ME类传入参数
        gallery.setAdapter(imageadapter);
       
        //设置Gallery的点击事件监听器,将受到点击的图片从 ImageView 中显示出来
        gallery.setOnItemClickListener(new Gallery.OnItemClickListener(){         
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
                // TODO Auto-generated method stub
                //显示该图片是几号
                Toast.makeText(Ex_Ctrl_10ME.this,
                                    "这是图片:"+position+"号", Toast.LENGTH_SHORT).show();
                //设置大图片
                imageview.setBackgroundResource(imageadapter.myImageIds[position]);
            }
        });
    }
}
⑥ 修改myImageAdapter.java 文件,实现相簿浏览效果
package zyf.Ex_Ctrl_10ME;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class myImageAdapter extends BaseAdapter{
    //自定义的类变量
    //变量声明
    int mGalleryItemBackground;
    private Context context;  //上下文
    //构建一Integer array 并取得预加载Drawable 的图片id ,这些图片都是存放于 res/drawable 文件夹下的
    public Integer[] myImageIds = { R.drawable.photo1, R.drawable.photo2,
                     R.drawable.photo3, R.drawable.photo4, R.drawable.photo5,R.drawable.photo6, };
   
    //自定义的构造方法
    public myImageAdapter(Context context) {
        // TODO Auto-generated constructor stub
        this.context=context;
        //使用在res/values/attrs.xml 中的<declare-styleable>定义的Gallery 属性.
        TypedArray typed_array=context.obtainStyledAttributes(R.styleable.Gallery);
        //取得Gallery 属性的Index id
       mGalleryItemBackground=typed_array.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
        // 让对象的styleable 属性能够反复使用
        typed_array.recycle();
    }
    //重写的方法getCount,返回图片数目
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return myImageIds.length;
    }
    // 重写的方法getItemId,返回图像的数组id 
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    //重写的方法getView,返回一View 对象
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        // 产生ImageView 对象
        ImageView imageview = new ImageView(context);
        // 设置图片给imageView 对象
        imageview.setImageResource(myImageIds[position]);
        // 重新设置图片的宽高
        imageview.setScaleType(ImageView.ScaleType.FIT_XY);
        // 重新设置Layout 的宽高
        imageview.setLayoutParams(new Gallery.LayoutParams(128, 128));
        // 设置 imageview 背景图
        imageview.setBackgroundResource(mGalleryItemBackground);
        // 返回imageView 对象
        return imageview;
    }
}
⑦ 结果
关键点
1. Gallery 控件 (画廊)
Gallery 控件 是 android 中的图片浏览控件。一个锁定中心条目并且拥有水平滚动列表的视图。如下图:
   
  Gallery(画廊)使用Theme_galleryItemBackground作为Gallery(画廊)适配器中的各视图的默认参数。如果你没有设置,你就需要调整一些Gallery(画廊)的属性,比如间距。
  Gallery(画廊)中的视图应该使用Gallery.LayoutParams作为它们的布局参数类型。参见Gallery tutorial。
  
API介绍:http://dev.10086.cn/cmdn/wiki/index.php?doc-view-4996.html
2. BaseAdapter
BaseAdaper 是 适配器Adapter类的子类,是一个抽象类。
18. SDCard 中文件搜索与File 类
示例代码
① 创建新工程
② 在string.xml 添加程序中要使用的字符串
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name"> myFileTest</string>
      <string name="showInput"> 输入关键字</string>
    <string name="toSearch"> 搜索</string>
    <string name="info"> 系统SDCard目录文件路径:\n</string>
    <string name="pleaseInput"> 请输入关键字!! </string>
    <string name="notFond"> 没有找到相关文件!! </string>
    <string name="pathError"> 读取路径出错!! </string>
</resources>
③ 修改main.xml 布局,添加两个TextView、一个EditText、一个Button
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:id="@+id/widget0"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
    android:id="@+id/Button_Search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="253px"
    android:layout_y="5px"
    android:text="@string/toSearch" >
</Button>
<EditText
    android:id="@+id/input_KEY_EditText"
    android:layout_width="112px"
    android:layout_height="52px"
    android:textSize="18sp"
    android:layout_x="119px"
    android:layout_y="4px" >
</EditText>
<TextView
    android:id="@+id/TextView_showIn"
    android:layout_width="103px"
    android:layout_height="29px"
    android:textSize="20sp"
    android:layout_x="5px"
    android:layout_y="16px"
    android:text="@string/showInput" >
</TextView>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="370px"
    android:layout_x="0px"
    android:layout_y="60px"
    android:id="@+id/TextView_Result" >
</TextView>
</AbsoluteLayout>
④ 修改mainActivity.java 文件,添加搜索功能
package zyf.myFileTest;
//导入程序使用的包
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class myFileTest extends Activity implements Button.OnClickListener {
    //Called when the activity is first created. 
    //定义程序要使用的类对象
    private File file;
    private String path;
    private String info;
    private String theKey_formInput;
    private TextView show_Result;
    private EditText input_SearchKey_Edit;
    private Button toSearch_Button;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置主屏布局为main.xml
        setContentView(R.layout.main);
        //通过findViewById()获取XML中的UI对象
        show_Result = (TextView) findViewById(R.id.TextView_Result);
        input_SearchKey_Edit = (EditText) findViewById(R.id.input_KEY_EditText);
        toSearch_Button = (Button) findViewById(R.id.Button_Search );
        //为搜索按钮添加点击事件监听器
        toSearch_Button.setOnClickListener(this);
        //初始化一个Fiel 对象,指定路径为/sdcard
        file = new File( "/sdcard" );
        //从xml中获取字符串
        info = getString(R.string.info);
    }
    //按钮点击事件处理
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //清空
        path = "";
        show_Result.setText("");
        //取得输入框中的要查询的Key
        theKey_formInput = input_SearchKey_Edit.getText().toString();
        //浏览文件
        BrowserFile( file );
    }
    //浏览文件方法
    public void BrowserFile(File file) {
        if (theKey_formInput.equals("")) {
            //如果输入框没有输入点击搜索按钮,提示输入
            Toast.makeText(this, getString(R.string.pleaseInput),
            Toast.LENGTH_SHORT).show();
        } else {
            //开始搜索文件
            ToSearchFiles(file);
            //搜索完毕后,如果搜到结果为空,提示没有找到
            if (show_Result.getText().equals("")) {
                Toast.makeText(this, getString(R.string.notFond),
                Toast.LENGTH_SHORT).show();
            }
        }
    }
    //开始搜索文件方法
    public void ToSearchFiles(File file) {
        //定义一个File文件数组,用来存放 /sdcard 目录下的文件或文件夹
        File[] the_Files = file.listFiles() ;
        //通过遍历所有文件和文件夹
        for (File tempF : the_Files) {
            if (tempF.isDirectory()) {
                ToSearchFiles(tempF);
                //如果是文件夹的话继续遍历搜索
            } else
           {
            try {
                //是文件,进行比较,如果文件名称中包含输入搜索Key,则返回大于-1的值
                if (tempF.getName().indexOf(theKey_formInput) > -1) {
                    //获取符合条件文件的路径,进行累加
                    path += "\n" + tempF.getPath();
                    //显示结果的TextView显示信息和搜索到的路径
                    show_Result.setText(info + path);
                }
            } catch (Exception e) {
                // TODO: handle exception
                //如果路径找不到,提示出错
                Toast.makeText(this, getString(R.string.pathError),Toast.LENGTH_SHORT).show();
            }
            }
        }
    }
}
⑤ 结果
关键点
1. 文件操作使用的 java 包
android 的文件搜索操作 是用的 java.io.file 包。
android 的文件读写 是跟 javaSE 相同的,都是使用的I/O流。需要用到的是 java.io.FileInputStream 包 和 java.io.FileOutputStream 包。可以通过 context.openFileOutput 和 context.openFileInput 的到输出和输入的流对象。
2. for循环 for( int x : n)
这个for循环是JDK1.5的新特性泛型的for循环。
   以下为例,两个for循环其实效果等同,那个更简单呢?
   第二个for循环在编译的时候会强直检查list中的对象类型是否是UserBean类型,如果不是会报编译错误
   第一个for循环编译没有问题,会在运行的时候报错
   相比之下第二种方法对于程序的稳定性更有利,而且不用显示的类型转换,提升了软件性能,泛型编程也是JAVA提倡的。
   for(int loop=0;loop<list.size();loop++){
           UserBean bean = (UserBean )list.get(loop); //显示的类型转换
           System.out.println(UserBean .getName());
   }
   for(UserBean bean : list ) {
         System.out.println(bean.getName());
   }
标签:
原文地址:http://www.cnblogs.com/wj033/p/4569710.html