2012년 11월 9일 금요일
센차터치2 + 폰갭 소스공개 - 이미지뷰어 1탄
제 책인 센차터치 + 폰갭2를 공부함으로서 최종적으로 만들수 있는 결과입니다.
만화를 보기위해 만든 어플입니다. 저작권상 만화를 캡쳐해서 올리지 못한게 조금 아쉽네요...
센차터치2 + 폰갭(안드로이드 환경) + 폰갭 플러그인 기술을 적용했습니다...
MVC모델을 준수했습니다. (책에는비 MVC를 기준으로 설명했고 새로운 유형이 나오면 MVC를 똑같은 기능을 넣어 제공했습니다... 둘을 비교하면 MVC가 어떠한 형태로 구현되는지 알수 있습니다...
1. 폴더를 먼저 올립니다. 소스를 보면 안드로이드 패키지와 폰갭 그리고 하단은 플러그인에 관련된 소스입니다...
가급적 쉽게 구현하였으므로 책을 따라하면 만드실 수 있습니다.
2. MVC 구조를 올립니다. MVC 구조를 살펴보시면 VIEW와 Controller, Model이 어떻게 구성되고 기타
Common과 같은 폴더의 구성을 보실 수 있습니다... (공부를 잘했다면 이해하실 수 있습니다.)
MVC 구조중 상단은 폴더와 파일목록을 보는 화면에 대한 Controller기준이며 하단은 만화를 보기위한 화면에 대한
컨트롤러입니다.
3. 구조를 이해하기 위해 폴더보기를 사진을 먼저 보여드립니다. 안드로이드 안에있는 각 폴더별로 이미지를 불러와
3장까지 보여주는 기능입니다....
4. 파일보기입니다. 해당 폴더의 파일이 나옵니다.. 파일을 스크롤 하여 아래로 내리면 10건씩 붙게 됩니다....
지금은 리스트가 메모리 관리에 큰 문제가 없지만... 이전에 만든거라... 30건을 유지하며 상위 10건은 삭제하도록 처리했습니
다... 따라서 리스트는 아무리 위 아래로 스크롤 해도 30건만 나옵니다....
5. 다음은 파일리스트 중 하나를 클릭하면 상세화면이 나옵니다...
이화면이 만화이어야 하는데..저작권 때문에 다른 이미지로 대체했습니다...
만화를 손가락으로 이동하여 페이지를 이동시킬 수 있습니다... 상세화면도...Carousel에서
딱 30장만 보이도록 컨트롤 했습니다... 앞뒤로 이동이 가능하고 만화를 다보고 파일목록으로 다시 이동할 경우
해당 만화를 보았던 곳으로 파일의 리스트가 자동 계산하여 이동하도록 처리했습니다...
(이부분이 센차터치 갤러리를 만드는 핵심구현부분입니다..)
6. 이 화면을 클릭하면 이미지 상세화면이 나오는데 확대 축소가 가능하도록 처리했습니다. 이화면은
생략합니다....
여기까지가 개요입닏. 2탄부터 소스를 설명합니다...계속...
2012년 11월 8일 목요일
센차터치2 + 폰갭 코믹뷰어 소스공개 4탄
이제 폰갭쪽 소스로 넘어옵니다... 폰갭소스는 1탄에서 폰 폴더 중 하단에 있는 부분입니다.
제가 안드로이드만 알고 아이폰은 잘 모르는 관계로 이부분은 안드로이드 기준으로 설명드립니다...
먼저 Activity를 살펴보겠습니다. 안드로이드가 이해되지 않으시면
센차터치2 + 폰갭의 안드로이드 설치 부분을 살펴보세요...
ImageViewrActivity.java 파일입니다.. --------------------------------
조금 복잡해진 부분이 있죠... Configuration.ORIENTATION_LANDSCAPE 와 PORTRAIT 부분이 있는데
왜이리 복잡해 졌을까요?????
만화를 볼때 가로모드까지 하단광고를 넣으면 .. 만화를 보기가 힘들어집니다...
그래서 세로모드만 애드몹 광고를 보여주도록 바꿔보았습니다... 몇시간 고민했네요...TT..
package com.lbo.imageviewer;
import com.google.ads.*;
import android.app.Activity;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.apache.cordova.*;
public class ImageViewerActivity extends DroidGap implements SensorEventListener {
/** Called when the activity is first created. */
AdView adView = null;
LinearLayout layout = null;
boolean isInit = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
adView = new AdView(this, AdSize.BANNER, "a1504841c828d31");
layout = super.root;
layout.addView( adView );
adView.setVisibility(View.VISIBLE);
adView.loadAd(new AdRequest());
if(getResources().getConfiguration().orientation ==Configuration.ORIENTATION_LANDSCAPE)
{
try
{
layout.removeView( adView );
}
catch(Exception e){}
}
isInit = true;
}
@Override
public void onConfigurationChanged(Configuration newConfig){
android.util.Log.i("", "--------------------come in");
super.onConfigurationChanged(newConfig);
if(isInit == true)
{
if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
try
{
layout.removeView(adView);
}
catch(Exception exTemp){}
layout.addView(adView);
}
else if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
try
{
layout.removeView(adView);
}
catch(Exception ex){}
}
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent arg0) {
}
}
다음은 폰갭 플러그인 부분입니다.... 플러그인의 사용도 책의 내용에 포함됩니다...
어디어디를 바꾸는지는 잘 읽어보시면 나옵니다....
ExecFile.java 파일입니다... --------------------------------------------
크게 2가지 기능이 있습니다.
처음 폴더리스트를 열때.. 폴더를 검색해서 이미지를 조회해 오는 기능이 있습니다...
두번째로는 파일목록의 파일 리스트를 조회해 오는 기능이 있습니다..
물론 이 기능이 폰갭의 파일API에도 있습니다.... 한데.. 속도가 좀 느려서요...App에서 바로 처리하도록
폰갭 플러그인으로 개발했습니다...
package com.phonegap.plugin.execfile;
import java.io.File;
import java.util.List;
import java.util.Vector;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
public class ExecFile extends Plugin {
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.trim().equals("exec")) {
result = this.exec(args.getString(0), args.optJSONObject(1).getString("package"));
}
else if (action.equals("getPackageList")) {
result = this.getPackageList(args.getString(0));
}
else if (action.equals("searchFile")) {
result = this.searchFile(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
else if (action.equals("searchDir")) {
result = this.searchDir(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
return new PluginResult(status, result);
} catch (Exception e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
public String exec(String inputFile, String inputPackage) {
try
{
String mimeType = "";
int S = inputFile.lastIndexOf(".");
String extName = inputFile.substring(S);
extName = extName.toLowerCase();
if( extName.equals(".gif") ||
extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp"))
{
mimeType = "image/*";
}
else if( extName.equals(".mp3")||
extName.equals(".ogg") ||
extName.equals(".3ga"))
{
mimeType = "audio/*";
}
else if( extName.equals(".mp4") ||
extName.equals(".kmv") ||
extName.equals(".avi"))
{
mimeType = "video/*";
}
else if( extName.equals(".html") ||
extName.equals(".xml") ||
extName.equals(".css") ||
extName.equals(".htm"))
{
mimeType = "text/html";
}
else if( extName.equals(".text") ||
extName.equals(".txt") ||
extName.equals(".doc") ||
extName.equals(".info"))
{
mimeType = "text/*";
}
else if( extName.equals(".pdf"))
{
mimeType = "application/pdf";
}
else if( extName.equals(".rtf"))
{
mimeType = "application/rtf";
}
else if( extName.equals(".xls") ||
extName.equals(".xlsx"))
{
mimeType = "application/vnd.ms-wxcel";
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addCategory(intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.parse(inputFile), mimeType);
this.ctx.startActivity(intent);
}
catch(Exception ex)
{
Toast.makeText(this.ctx.getContext() , "Can't Open File", 5000).show();
}
return "";
}
public String getPackageList(String inputFile) {
Log.i("", "getPackageList:" + inputFile);
PackageManager pm = this.ctx.getContext().getPackageManager();
List<ApplicationInfo> packs = pm.getInstalledApplications(
PackageManager.GET_META_DATA);
String result = "[";
int count_i = 0;
for(int i=0; i<packs.size(); i++ ){
ApplicationInfo app= (ApplicationInfo)packs.get(i);
if(app.packageName.contains("com.android") || app.packageName.contains("com.google"))
{
if(count_i != 0)
result = result + ",";
result = result + "{'l': '" + app.loadLabel(pm).toString() + "'," +
"'p':'" + app.packageName + "'}";
count_i++;
}
}
result = result + "]";
result = result.replace("\n","");
return result;
}
public String searchFile(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFileList(pathName, inputValue);
File[] files = fileList.getFiles();
int size = files.length;
for(int i=0; i< size-1; i++)
{
String fileName = files[i].getAbsolutePath();
for(int j=i+1; j < size; j++)
{
if(fileName.compareTo(files[j].getName()) < 0)
{
File tempFile = files[i];
files[i] = files[j];
files[j] = tempFile;
}
}
}
for(int i=0; i<size;i++)
{
if(i != 0)
{
result = result + ",";
}
String fileName = files[i].getAbsolutePath();
String fileNameSmpl = files[i].getName();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
result = result + "{'id':'" + i + "', 'subject':'" + fileNameSmpl + "', 'content':'" + filePath + "', 'img':'" + fileName + "'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
public String searchDir(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFolderList(pathName, inputValue);
File[] files = fileList.getFiles();
int size = files.length;
int divRowSize = 0;
String[][] pathDiv = new String[size][20];
String[][] fileDiv = new String[size][20];
int[] divSize = new int[size];
for(int i=0; i<size;i++)
{
String fileName = files[i].getAbsolutePath();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
Log.i("", "filePath:" + filePath);
Log.i("", "fileName:" + fileName);
boolean isExist = false;
for(int j=0; j< divRowSize; j++)
{
if(pathDiv[j][0].equals(filePath))
{
pathDiv [j][divSize[j]] = filePath;
fileDiv [j][divSize[j]] = fileName;
divSize[j]++;
isExist = true;
break;
}
}
if(isExist== false)
{
pathDiv [divRowSize][0] = filePath;
fileDiv [divRowSize][0] = fileName;
divSize[divRowSize]++;
divRowSize++;
}
}
result = "";
for(int i=0; i< divRowSize;i++)
{
if(i != 0)
{
result = result + ",";
}
result = result + "{ 'path': '" + pathDiv[i][0] + "',";
for(int j=0;j<divSize[i];j++)
{
result = result + "'img" + j + "':'" + fileDiv[i][j] + "',";
}
for (int j=divSize[i]; j <5; j++)
{
result = result + "'img" + j + "':'./img/blank.png',";
}
result= result + " 'isFile':'N'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
class FileEntity
{
Vector vecFileList;
FileEntity()
{
vecFileList = new Vector();
}
public File[] getFiles()
throws Exception
{
File[] files = new File[vecFileList.size()];
for(int i=0; i<vecFileList.size(); i++)
{
files[i] = (File)vecFileList.get(i);
}
return files;
}
public File[] getFileList(String path, String searchText)
throws Exception
{
File dir = new File(path);
File[] files = dir.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
vecFileList.add(file.getAbsoluteFile());
}
}
}
}
return files;
}
public File[] getFolderList(String path, String searchText)
throws Exception
{
File dir = new File(path);
Log.i("", "" + path);
File[] files = dir.listFiles();
int tempCount = 0;
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
if(tempCount < 3)
{
vecFileList.add(file.getAbsoluteFile());
}
tempCount++;
}
}
}
else if(file.isDirectory())
{
getFolderList(file.getCanonicalPath().toString(), searchText);
}
}
return files;
}
}
}
도움이 되셨나요.... 나름 도움도되고 책선전도 되고..해서요....
센차터치2 + 폰갭의 부록에 나오는 이미지(코믹)뷰어에 대한 설명이었습니다...
앞부분을 이해하셔야 처리하실수 있습니다...
부록에는 파일매니져도 있는데요... 파일목록에서 파일을 클릭하면 해당 파일을 복사하거나 삭제, 이동할수 있는 기능이외에
동영상을 클릭하면 동영상이 출력되고, 이미지를 클릭하면 이미지가 보이고. 음악을 클릭하면 음악이 보이고
pdf를 클릭하면 pdf가 보이도록 처리되는 기능을 만들어 보았습니다...한데 이소스는 MVC가 아니라 좀 지저분합니다.
아뭏든 이미지 뷰어를 MVC로 구성해서 올려보았습니다...
센차터치를 공부하는데 도움이 되셨으면 합니다....
참.... 한가지 갤럭시S3에서 올릴때 한가지 주의사항입니다... 그냥올리면 실행이 안돼죠...
index.html의 소스를 잘 살펴보세요.. 그리고 그대로 올리세요. 그럼 실행됩니다.
참고로 전 삼국지 만화를 이걸로 다 보았습니다.. 볼만 합니다....
그럼...도움이되셨길...
제가 안드로이드만 알고 아이폰은 잘 모르는 관계로 이부분은 안드로이드 기준으로 설명드립니다...
먼저 Activity를 살펴보겠습니다. 안드로이드가 이해되지 않으시면
센차터치2 + 폰갭의 안드로이드 설치 부분을 살펴보세요...
ImageViewrActivity.java 파일입니다.. --------------------------------
조금 복잡해진 부분이 있죠... Configuration.ORIENTATION_LANDSCAPE 와 PORTRAIT 부분이 있는데
왜이리 복잡해 졌을까요?????
만화를 볼때 가로모드까지 하단광고를 넣으면 .. 만화를 보기가 힘들어집니다...
그래서 세로모드만 애드몹 광고를 보여주도록 바꿔보았습니다... 몇시간 고민했네요...TT..
package com.lbo.imageviewer;
import com.google.ads.*;
import android.app.Activity;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.apache.cordova.*;
public class ImageViewerActivity extends DroidGap implements SensorEventListener {
/** Called when the activity is first created. */
AdView adView = null;
LinearLayout layout = null;
boolean isInit = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
adView = new AdView(this, AdSize.BANNER, "a1504841c828d31");
layout = super.root;
layout.addView( adView );
adView.setVisibility(View.VISIBLE);
adView.loadAd(new AdRequest());
if(getResources().getConfiguration().orientation ==Configuration.ORIENTATION_LANDSCAPE)
{
try
{
layout.removeView( adView );
}
catch(Exception e){}
}
isInit = true;
}
@Override
public void onConfigurationChanged(Configuration newConfig){
android.util.Log.i("", "--------------------come in");
super.onConfigurationChanged(newConfig);
if(isInit == true)
{
if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
try
{
layout.removeView(adView);
}
catch(Exception exTemp){}
layout.addView(adView);
}
else if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
try
{
layout.removeView(adView);
}
catch(Exception ex){}
}
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent arg0) {
}
}
다음은 폰갭 플러그인 부분입니다.... 플러그인의 사용도 책의 내용에 포함됩니다...
어디어디를 바꾸는지는 잘 읽어보시면 나옵니다....
ExecFile.java 파일입니다... --------------------------------------------
크게 2가지 기능이 있습니다.
처음 폴더리스트를 열때.. 폴더를 검색해서 이미지를 조회해 오는 기능이 있습니다...
두번째로는 파일목록의 파일 리스트를 조회해 오는 기능이 있습니다..
물론 이 기능이 폰갭의 파일API에도 있습니다.... 한데.. 속도가 좀 느려서요...App에서 바로 처리하도록
폰갭 플러그인으로 개발했습니다...
package com.phonegap.plugin.execfile;
import java.io.File;
import java.util.List;
import java.util.Vector;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
public class ExecFile extends Plugin {
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.trim().equals("exec")) {
result = this.exec(args.getString(0), args.optJSONObject(1).getString("package"));
}
else if (action.equals("getPackageList")) {
result = this.getPackageList(args.getString(0));
}
else if (action.equals("searchFile")) {
result = this.searchFile(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
else if (action.equals("searchDir")) {
result = this.searchDir(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
return new PluginResult(status, result);
} catch (Exception e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
public String exec(String inputFile, String inputPackage) {
try
{
String mimeType = "";
int S = inputFile.lastIndexOf(".");
String extName = inputFile.substring(S);
extName = extName.toLowerCase();
if( extName.equals(".gif") ||
extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp"))
{
mimeType = "image/*";
}
else if( extName.equals(".mp3")||
extName.equals(".ogg") ||
extName.equals(".3ga"))
{
mimeType = "audio/*";
}
else if( extName.equals(".mp4") ||
extName.equals(".kmv") ||
extName.equals(".avi"))
{
mimeType = "video/*";
}
else if( extName.equals(".html") ||
extName.equals(".xml") ||
extName.equals(".css") ||
extName.equals(".htm"))
{
mimeType = "text/html";
}
else if( extName.equals(".text") ||
extName.equals(".txt") ||
extName.equals(".doc") ||
extName.equals(".info"))
{
mimeType = "text/*";
}
else if( extName.equals(".pdf"))
{
mimeType = "application/pdf";
}
else if( extName.equals(".rtf"))
{
mimeType = "application/rtf";
}
else if( extName.equals(".xls") ||
extName.equals(".xlsx"))
{
mimeType = "application/vnd.ms-wxcel";
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addCategory(intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.parse(inputFile), mimeType);
this.ctx.startActivity(intent);
}
catch(Exception ex)
{
Toast.makeText(this.ctx.getContext() , "Can't Open File", 5000).show();
}
return "";
}
public String getPackageList(String inputFile) {
Log.i("", "getPackageList:" + inputFile);
PackageManager pm = this.ctx.getContext().getPackageManager();
List<ApplicationInfo> packs = pm.getInstalledApplications(
PackageManager.GET_META_DATA);
String result = "[";
int count_i = 0;
for(int i=0; i<packs.size(); i++ ){
ApplicationInfo app= (ApplicationInfo)packs.get(i);
if(app.packageName.contains("com.android") || app.packageName.contains("com.google"))
{
if(count_i != 0)
result = result + ",";
result = result + "{'l': '" + app.loadLabel(pm).toString() + "'," +
"'p':'" + app.packageName + "'}";
count_i++;
}
}
result = result + "]";
result = result.replace("\n","");
return result;
}
public String searchFile(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFileList(pathName, inputValue);
File[] files = fileList.getFiles();
int size = files.length;
for(int i=0; i< size-1; i++)
{
String fileName = files[i].getAbsolutePath();
for(int j=i+1; j < size; j++)
{
if(fileName.compareTo(files[j].getName()) < 0)
{
File tempFile = files[i];
files[i] = files[j];
files[j] = tempFile;
}
}
}
for(int i=0; i<size;i++)
{
if(i != 0)
{
result = result + ",";
}
String fileName = files[i].getAbsolutePath();
String fileNameSmpl = files[i].getName();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
result = result + "{'id':'" + i + "', 'subject':'" + fileNameSmpl + "', 'content':'" + filePath + "', 'img':'" + fileName + "'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
public String searchDir(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFolderList(pathName, inputValue);
File[] files = fileList.getFiles();
int size = files.length;
int divRowSize = 0;
String[][] pathDiv = new String[size][20];
String[][] fileDiv = new String[size][20];
int[] divSize = new int[size];
for(int i=0; i<size;i++)
{
String fileName = files[i].getAbsolutePath();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
Log.i("", "filePath:" + filePath);
Log.i("", "fileName:" + fileName);
boolean isExist = false;
for(int j=0; j< divRowSize; j++)
{
if(pathDiv[j][0].equals(filePath))
{
pathDiv [j][divSize[j]] = filePath;
fileDiv [j][divSize[j]] = fileName;
divSize[j]++;
isExist = true;
break;
}
}
if(isExist== false)
{
pathDiv [divRowSize][0] = filePath;
fileDiv [divRowSize][0] = fileName;
divSize[divRowSize]++;
divRowSize++;
}
}
result = "";
for(int i=0; i< divRowSize;i++)
{
if(i != 0)
{
result = result + ",";
}
result = result + "{ 'path': '" + pathDiv[i][0] + "',";
for(int j=0;j<divSize[i];j++)
{
result = result + "'img" + j + "':'" + fileDiv[i][j] + "',";
}
for (int j=divSize[i]; j <5; j++)
{
result = result + "'img" + j + "':'./img/blank.png',";
}
result= result + " 'isFile':'N'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
class FileEntity
{
Vector vecFileList;
FileEntity()
{
vecFileList = new Vector();
}
public File[] getFiles()
throws Exception
{
File[] files = new File[vecFileList.size()];
for(int i=0; i<vecFileList.size(); i++)
{
files[i] = (File)vecFileList.get(i);
}
return files;
}
public File[] getFileList(String path, String searchText)
throws Exception
{
File dir = new File(path);
File[] files = dir.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
vecFileList.add(file.getAbsoluteFile());
}
}
}
}
return files;
}
public File[] getFolderList(String path, String searchText)
throws Exception
{
File dir = new File(path);
Log.i("", "" + path);
File[] files = dir.listFiles();
int tempCount = 0;
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
if(tempCount < 3)
{
vecFileList.add(file.getAbsoluteFile());
}
tempCount++;
}
}
}
else if(file.isDirectory())
{
getFolderList(file.getCanonicalPath().toString(), searchText);
}
}
return files;
}
}
}
도움이 되셨나요.... 나름 도움도되고 책선전도 되고..해서요....
센차터치2 + 폰갭의 부록에 나오는 이미지(코믹)뷰어에 대한 설명이었습니다...
앞부분을 이해하셔야 처리하실수 있습니다...
부록에는 파일매니져도 있는데요... 파일목록에서 파일을 클릭하면 해당 파일을 복사하거나 삭제, 이동할수 있는 기능이외에
동영상을 클릭하면 동영상이 출력되고, 이미지를 클릭하면 이미지가 보이고. 음악을 클릭하면 음악이 보이고
pdf를 클릭하면 pdf가 보이도록 처리되는 기능을 만들어 보았습니다...한데 이소스는 MVC가 아니라 좀 지저분합니다.
아뭏든 이미지 뷰어를 MVC로 구성해서 올려보았습니다...
센차터치를 공부하는데 도움이 되셨으면 합니다....
참.... 한가지 갤럭시S3에서 올릴때 한가지 주의사항입니다... 그냥올리면 실행이 안돼죠...
index.html의 소스를 잘 살펴보세요.. 그리고 그대로 올리세요. 그럼 실행됩니다.
참고로 전 삼국지 만화를 이걸로 다 보았습니다.. 볼만 합니다....
그럼...도움이되셨길...
센차터치2 + 폰갭 코믹뷰어 소스공개 3탄
다시 3탄으로 이어집니다....
자... 이제 상세화면을 살펴보겠습니다... 1탄의 이미지를 기억하세요... 상세화면은
파일목록에서 하나를 클릭해서 해당 폴더의 파일을 만화보듯이 손가락으로 넘겨서 만화를 보는 곳입니다.....
먼저 뷰를 살펴보겠습니다...
GalleryDetailView.js 파일입니다. ----------------------------
뭘를 가져왔나요.... 툴바, Carousel이 있죠.. Carousel을 잘 살펴보셔야 합니다.
Ext.define("Gallery.view.GalleryDetailView", {
extend: 'Ext.Panel',
xtype:'gallerydetailview',
requires:[
'Ext.Panel',
'Ext.Toolbar',
'Gallery.view.GalleryDetailCarousel'
],
config:{
fullscreen: true,
layout: {
type: 'vbox',
align: 'stretch',
},
items:[
{
name:'subjectToolbar',
xtype: 'toolbar',
height:40,
docked: 'top',
title:'Detail',
layout: {
type:'hbox',
align: 'stretch'
},
items:[
{
html:'<img src="./img/folder_black_open.png" height="30">',
name:'backList',
docked:'left',
},
{
xtype:'spacer',
},
{
html:'<img src="./img/search1.png" height="30">',
name:'chgSize',
docked:'right',
}]
},
{
xtype:'gallerydetailcarousel', //gallerydetail.carousel
name:'gallerydetailcarousel',
flex:1,
}],
}
});
GalleryDetailCarousel.js 파일입니다. ---------------------------
소스가 허전하죠... MVC로 하지 않았다면 소스가 엄청 있었을 겁니다.
Ext.define("Gallery.view.GalleryDetailCarousel", {
extend: 'Ext.Carousel',
xtype:'gallerydetailcarousel',
config:{
// 화면의 상하단 버튼을 확인
flex:1,
defaults: {
cls: 'card'
},
indicator:false,
items:[]
}
});
Carousel에 들어갈 화면이 필요하겠죠..... 그 안에서 돌아갈 화면입니다. 이미지를 담당하죠...
GalleryDetailCard.js 파일입니다. -------------------------------------
Ext.define("Gallery.view.GalleryDetailCard", {
extend:'Ext.Panel',
xtype:'gallerydetailcard',
galleryid:'0',
subject:'',
content:'',
img:'',
setImgCls:false,
config:{
height:'100%',
width:'100%',
scrollable:{
direction:'vertical',
directionLock:true,
},
layout:{
xtype:'vbox',
},
},
setPage:function(id, subject, content, img)
{
this.galleryid = id;
this.subject = subject;
this.content = content;
this.img = img;
this.setHtml('<img width="100%" src="' + this.img + '">');
this.setImgCls = true;
},
// 이미지 설정
setImg:function()
{
},
// 이미지 해제
releaseImg:function()
{
},
// 초기화
initialize:function(){
this.img='';
this.setImgCls = false;
this.flex = 1,
this.layout = {
type: 'vbox',
align:'stretch',
};
this.callParent();
}
});
확대창 보기입니다... 프로그램에 크게 중요하지 않으므로 무시하셔도 됩니다...
GalleryDetailCardPop.js 입니다. -------------------------------------------------------
Ext.define("Gallery.view.GalleryDetailCardPop", {
extend:'Ext.Panel',
xtype:'gallerydetailcardpop',
galleryid:'0',
subject:'',
content:'',
img:'',
popSize:'',
popRotate:'',
popState:0,
setImgCls:false,
config:{
fullscreen:true,
styleHtmlContent:true,
layout:{
xtype:'vbox',
},
scrollable:{
direction:'both',
directionLock:true
},
html:'',
items:[
{
xtype:'toolbar',
docked:'top',
height:40,
items:[
{
xtype:'button',
html:'<img src="./img/arrow_left.png" height="30">', // 방향전환
name:'popLeft'
},
{
xtype:'spacer'
},
{
xtype:'button',
html:'<img src="./img/delete.png" height="20">', // 나가기
name:'popClose'
},
{
xtype:'button',
html:'<img src="./img/minus1.png" height="20">', // 사이즈
name:'popSizeM'
},
{
xtype:'button',
html:'<img src="./img/add.png" height="20">', // 사이즈
name:'popSizeA'
},
{
xtype:'spacer'
},
{
xtype:'button',
html:'<img src="./img/arrow_right.png" height="30">', // 방향전환
name:'popRight'
}]
}],
},
setPage:function(id, subject, content, img, popSize, popRotate, panelWidth)
{
this.galleryid = id;
this.subject = subject;
this.content = content;
this.img = img;
this.popSize = popSize;
this.popRotate = popRotate;
var imgElement = document.createElement("img");
imgElement.src=this.img;
var tempWidth = imgElement.width;
var tempHeight = imgElement.height;
var tempCalc = tempHeight/tempWidth;
imgElement.width = window.screen.width * this.popSize * 0.01;
imgElement.height = imgElement.width * tempCalc;
this.setHtml('<font size=2>' + subject + '</font><BR><img height="' + imgElement.height + 'px" width="' + imgElement.width + 'px" src="' + this.img + '"> ');
this.setImgCls = true;
},
// 이미지 설정
setImg:function()
{
},
// 이미지 해제
releaseImg:function()
{
},
// 초기화
initialize:function(){
this.img='';
this.popSize='';
this.popRotate='';
this.setImgCls = false;
this.flex = 1,
this.layout = {
type: 'vbox',
align:'stretch',
};
this.callParent();
}
});
이제 가장중요한 controller입니다......
GalleryDetailController.js 파일입니다... 소스에 간단한 설명을 해놓았으니 잘 살펴보시기 바랍니다.....
Ext.define('Gallery.controller.GalleryDetailController', {
extend: 'Ext.app.Controller',
xtype:'gallerydetailcontroller',
name:'GalleryDetailController',
requires:[
'Ext.Ajax',
'Ext.Anim',
'Gallery.view.GalleryDetailCard',
'Gallery.common.GalleryData'
],
config: {
// 참조개체를 정의한다.
refs: {
galleryListView: 'gallerylistview',
galleryDetailView: 'gallerydetailview',
galleryDetailCard: 'gallerydetailcard',
galleryDetailCardPop: 'gallerydetailcardpop',
galleryDetailCarousel: 'gallerydetailview [name=gallerydetailcarousel]',
subjectToolbar : 'gallerydetailview [name=subjectToolbar]',
backList : 'gallerydetailview [name=backList]',
chgSize: 'gallerydetailview [name=chgSize]',
popLeft: 'gallerydetailcardpop [name=popLeft]',
popClose: 'gallerydetailcardpop [name=popClose]',
popSizeA: 'gallerydetailcardpop [name=popSizeA]',
popSizeM: 'gallerydetailcardpop [name=popSizeM]',
popRotate: 'gallerydetailcardpop [name=popRotate]',
popRight: 'gallerydetailcardpop [name=popRight]',
},
// 참조개체의 이벤트를 정의함.
control: {
// viewport로부터 화면의 가로세로 변환을 감지하여 이벤트를 처리함.
viewport:{
orientationchange: 'onOrien'
},
galleryDetailCarousel: {
activeitemchange: 'onCarouselChange'
},
backList:{
tap:'onBackList'
},
chgSize:{
tap:'onChgSize'
},
popLeft:{
tap:'onPopLeft'
},
popClose:{
tap:'onPopClose'
},
popSizeA:{
tap:'onPopSizeA'
},
popSizeM:{
tap:'onPopSizeM'
},
popRotate:{
tap:'onPopRotate'
},
popRight:{
tap:'onPopRight'
},
}
},
// 멤버변수
currPageNum:0,
carouselAdded:0,
imgDraw:false,
panelPop:'',
popState:0,
launch: function() {
},
// 가로세로가 변경될 경우 시간을 지연한다.
onOrien:function(viewport, orientation, width, height){
if(orientation == 'portrait')
{
var strtTime = new Date().getTime();
for(var i=0;i<10000; i++)
{
var endTime= new Date().getTime();
if((endTime - strtTime) > 500)
{
break;
}
}
}
},
// 파일목록에서 상세화면이 호출될때 메소드
setPage:function(cpage){
this.currPageNum = cpage;
this.setDataPos('first');
},
// 폰갭플러그인을 통해 목록을 가져옴.
callServer:function(inputPage)
{
var tempThis= this;
var startNum = (inputPage-1)* 10;
var lastNum = startNum + 10;
if(startNum > Gallery.common.GalleryData.totData.length)
{
this.currPageNum = this.currPageNum - 1;
alert('더이상 데이터가 없습니다.');
return;
}
if( Gallery.common.GalleryData.totData.length < lastNum )
{
lastNum = Gallery.common.GalleryData.totData.length;
}
var tempArray = Array (lastNum-startNum);
var j=0;
for(i = startNum; i< lastNum; i++)
{
tempArray[j] = Gallery.common.GalleryData.totData[i];
j++;
}
this.addProxyData(tempArray);
},
// 상세화면관련====================================
// 앞화면(리스트 조회에서) 클릭하였을 경우 보여주는 현재 화면의 위치
setDataPos:function(val)
{
if(val=='first')
{
for(i= this.getGalleryDetailCarousel().getItems().length-1; i >= this.carouselAdded;i--)
{
this.getGalleryDetailCarousel().removeAt(i);
}
}
var start_i = Gallery.common.GalleryData.minDataPos;
if(start_i< 0)
start_i=0;
for(i = start_i; i< Gallery.common.GalleryData.maxDataPos;i++)
{
try{ this.addArt(Gallery.common.GalleryData.orgData[i]); }catch(e){ console.log('오류무시'); }
}
this.getGalleryDetailCarousel().setActiveItem( Gallery.common.GalleryData.curDataPos - start_i);
this.getGalleryDetailView().imgDraw = true;
// 첫번째 호출일경우
if(val=='first')
{
console.log('첫번째위치 ');
var firstPos = Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos;
if(firstPos < 0)
firstPos = 0;
var detailCard = this.getGalleryDetailCarousel().getAt(firstPos + this.carouselAdded);
this.getSubjectToolbar().setTitle(detailCard.subject);
try
{
Gallery.common.GalleryData.curId = detailCard.galleryid;
}
catch(e){}
}
},
// 가져온 데이터받기이벤트
addProxyData:function(result)
{
if(result == null){
}
else
{
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
this.getGalleryDetailCarousel().removeAt(0 + this.carouselAdded);
}
}
this.addProxyDataSub(result);
}
},
// addProxyData로부터 호출됨
addProxyDataSub:function(result)
{
var temp = Gallery.common.GalleryData.maxDataPos;
for(i = 0; i< result.length; i++)
{
Gallery.common.GalleryData.orgData.push(result[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos + 10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos - 30;
if(Gallery.common.GalleryData.maxDataPos > Gallery.common.GalleryData.totDataPos)
{
Gallery.common.GalleryData.totDataPos = Gallery.common.GalleryData.maxDataPos;
}
for(i = 0; i< result.length; i++)
{
this.addArt(result[i]);
}
if(temp >= 30)
{
this.getGalleryDetailCarousel().setActiveItem(19);
}
},
// 데이터를 추가함
addData:function(result)
{
for(i = 0; i< result.length; i++)
{
this.addArt(result[i]);
}
},
// 데이터를 삽입함
insertData:function(result)
{
for(i = 9; i>=0; i--)
{
this.insertArt(result[i]);
}
},
// 커로우절화면====================================
onCarouselChange:function( a, index1,index2){
console.log('움직였다.' + index1 + "." + index2);
if(this.getGalleryDetailView().imgDraw == true)
{
// 화면갱신
var curIndex = Number(this.getGalleryDetailCarousel().getActiveIndex());
{
{
// 페이지가 움직일때 Title설정
var detailCard =
this.getGalleryDetailCarousel().getAt(curIndex+this.carouselAdded);
Gallery.common.GalleryData.curId = detailCard.galleryid;
// 타이틀바 설정 (적절히 크기 등 수정요함)
this.getSubjectToolbar().setTitle(detailCard.subject);
}
}
// 오른쪽으로 이동
if(curIndex == this.getGalleryDetailCarousel().getItems().length-1-this.carouselAdded)
{
// 현재 MAX값보다 큰 값을 가져올 경우 서버로부터 데이터를 요청함.
if(Gallery.common.GalleryData.maxDataPos >= Gallery.common.GalleryData.totDataPos)
{
this.currPageNum = this.currPageNum+1;
this.callServer(this.currPageNum);
}
else
{
// 현재위치보다 작고 30건 이상일 경우 이미 불러온 10건을 리스트에 추가함.
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
this.getGalleryDetailCarousel().removeAt(0 + this.carouselAdded);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos;
i< Gallery.common.GalleryData.maxDataPos+10;
i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos+10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
this.addData(result);
}
}
}
else if(curIndex == 0)
{
// 맨 왼쪽으로 왔을 경우
console.log("왼쪽으로 이동");
if(Gallery.common.GalleryData.maxDataPos > 30)
{
// 30건 이상이 있을 경우 오른쪽 10건을 지우고 왼쪽 10건을 추가함.
for(i=9; i>=0;i--)
{
this.getGalleryDetailCarousel().removeAt(i + 20 + this.carouselAdded);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos-40;
i< Gallery.common.GalleryData.maxDataPos-30;
i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos-10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
this.insertData(result);
this.getGalleryDetailCarousel().setActiveItem(10);
}
}
}
if(this.popState == 1)
{
this.pageRefresh();
}
},
// 앞화면(리스트 조회에서) 클릭하였을 경우 보여주는 현재 화면의 위치
setDetailDataPos:function(val)
{
if(val=='first')
{
for(i=this.getGalleryDetailCarousel().getItems().length-1; i>=this.carouselAdded;i--)
{
this.getGalleryDetailCarousel().removeAt(i);
}
}
var start_i = Gallery.common.GalleryData.minDataPos;
if(start_i< 0)
start_i=0;
for(i = start_i; i< Gallery.common.GalleryData.maxDataPos;i++)
{
try{ this.addArt(Gallery.common.GalleryData.orgData[i]); }catch(e){}
}
// 페이지를 이동시킨다.
this.getGalleryDetailCarousel().setActiveItem( Gallery.common.GalleryData.curDataPos - start_i);
this.getGalleryDetailView().imgDraw = true;
// 첫번째 호출일경우
if(val=='first')
{
var firstPos = Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos;
if(firstPos < 0)
firstPos = 0;
var detailCard = this.getGalleryDetailCarousel().getAt(firstPos+this.carouselAdded);
try
{
Gallery.common.GalleryData.curId = detailCard.galleryid;
}
catch(e){ console.log('에러무시' ); }
}
},
// GalleryDetailCard에 이미지를 넣은뒤 Carousel에 추가함
addArt:function(photodata){
var detailCard = new Ext.create('Gallery.view.GalleryDetailCard');
detailCard.setPage( photodata.id,
photodata.subject,
photodata.content,
photodata.img);
this.getGalleryDetailCarousel().add(detailCard);
},
// 앞쪽에 CardDetailCard를 추가함
insertArt:function(photodata) {
var detailCard = new Ext.create('Gallery.view.GalleryDetailCard');
detailCard.setPage( photodata.id,
photodata.subject,
photodata.content,
photodata.img);
this.getGalleryDetailCarousel().insert(0 + this.carouselAdded, detailCard);
},
// 파일목록으로 돌아감.
onBackList:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
this.getGalleryDetailView().hide();
this.getGalleryListView().show();
this.getApplication().getController('GalleryController').returnAddMsg(this.currPageNum);
},
// 상세확대창으로 이동
onChgSize:function()
{
this.getGalleryDetailView().hide();
this.getGalleryDetailCardPop().show();
this.popState = 1;
this.pageRefresh();
},
// 확대창에서 왼쪽이미지로 변경
onPopLeft:function()
{
this.getGalleryDetailCarousel().previous();
},
// 확대창을 닫음
onPopClose:function()
{
this.popState = 0;
this.getGalleryDetailCardPop().hide();
this.getGalleryDetailView().show();
},
// 확대창에서 크기를 늘림
onPopSizeA:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
Gallery.common.GalleryData.popSize = Gallery.common.GalleryData.popSize + 10;
this.pageRefresh();
},
// 확대창에서 크기를 줄임
onPopSizeM:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
Gallery.common.GalleryData.popSize = Gallery.common.GalleryData.popSize - 10;
this.pageRefresh();
},
// 확대창 이미지를 회전시킨 (미사용)
onPopRotate:function()
{
if(Gallery.common.GalleryData.popRotate == "rotate0")
Gallery.common.GalleryData.popRotate = "rotate90";
else if(Gallery.common.GalleryData.popRotate == "rotate90")
Gallery.common.GalleryData.popRotate = "rotate180";
else if(Gallery.common.GalleryData.popRotate == "rotate180")
Gallery.common.GalleryData.popRotate = "rotate270"
else if(Gallery.common.GalleryData.popRotate == "rotate270")
Gallery.common.GalleryData.popRotate = "rotate0";
this.pageRefresh();
},
// 확대창 이미지를 오른쪽 이미지로 대체
onPopRight:function()
{
this.getGalleryDetailCarousel().next();
},
// 확대창의 조작이 있은 후 화면을 갱신함
pageRefresh:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
this.getGalleryDetailCardPop().setPage(
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].id,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].subject,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].content,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].img,
Gallery.common.GalleryData.popSize,
Gallery.common.GalleryData.popRotate,
window.screen.width);
}
});
센차터치쪽 소스는 다 보았습니다.... 어떠신지요..... Controller와 Controller간 호출도 살펴보세요...
다음은 폰갭 플러그인을 살펴봐야 할것 같네요.. 계속 4탄으로 이어집니다.
자... 이제 상세화면을 살펴보겠습니다... 1탄의 이미지를 기억하세요... 상세화면은
파일목록에서 하나를 클릭해서 해당 폴더의 파일을 만화보듯이 손가락으로 넘겨서 만화를 보는 곳입니다.....
먼저 뷰를 살펴보겠습니다...
GalleryDetailView.js 파일입니다. ----------------------------
뭘를 가져왔나요.... 툴바, Carousel이 있죠.. Carousel을 잘 살펴보셔야 합니다.
Ext.define("Gallery.view.GalleryDetailView", {
extend: 'Ext.Panel',
xtype:'gallerydetailview',
requires:[
'Ext.Panel',
'Ext.Toolbar',
'Gallery.view.GalleryDetailCarousel'
],
config:{
fullscreen: true,
layout: {
type: 'vbox',
align: 'stretch',
},
items:[
{
name:'subjectToolbar',
xtype: 'toolbar',
height:40,
docked: 'top',
title:'Detail',
layout: {
type:'hbox',
align: 'stretch'
},
items:[
{
html:'<img src="./img/folder_black_open.png" height="30">',
name:'backList',
docked:'left',
},
{
xtype:'spacer',
},
{
html:'<img src="./img/search1.png" height="30">',
name:'chgSize',
docked:'right',
}]
},
{
xtype:'gallerydetailcarousel', //gallerydetail.carousel
name:'gallerydetailcarousel',
flex:1,
}],
}
});
GalleryDetailCarousel.js 파일입니다. ---------------------------
소스가 허전하죠... MVC로 하지 않았다면 소스가 엄청 있었을 겁니다.
Ext.define("Gallery.view.GalleryDetailCarousel", {
extend: 'Ext.Carousel',
xtype:'gallerydetailcarousel',
config:{
// 화면의 상하단 버튼을 확인
flex:1,
defaults: {
cls: 'card'
},
indicator:false,
items:[]
}
});
Carousel에 들어갈 화면이 필요하겠죠..... 그 안에서 돌아갈 화면입니다. 이미지를 담당하죠...
GalleryDetailCard.js 파일입니다. -------------------------------------
Ext.define("Gallery.view.GalleryDetailCard", {
extend:'Ext.Panel',
xtype:'gallerydetailcard',
galleryid:'0',
subject:'',
content:'',
img:'',
setImgCls:false,
config:{
height:'100%',
width:'100%',
scrollable:{
direction:'vertical',
directionLock:true,
},
layout:{
xtype:'vbox',
},
},
setPage:function(id, subject, content, img)
{
this.galleryid = id;
this.subject = subject;
this.content = content;
this.img = img;
this.setHtml('<img width="100%" src="' + this.img + '">');
this.setImgCls = true;
},
// 이미지 설정
setImg:function()
{
},
// 이미지 해제
releaseImg:function()
{
},
// 초기화
initialize:function(){
this.img='';
this.setImgCls = false;
this.flex = 1,
this.layout = {
type: 'vbox',
align:'stretch',
};
this.callParent();
}
});
확대창 보기입니다... 프로그램에 크게 중요하지 않으므로 무시하셔도 됩니다...
GalleryDetailCardPop.js 입니다. -------------------------------------------------------
Ext.define("Gallery.view.GalleryDetailCardPop", {
extend:'Ext.Panel',
xtype:'gallerydetailcardpop',
galleryid:'0',
subject:'',
content:'',
img:'',
popSize:'',
popRotate:'',
popState:0,
setImgCls:false,
config:{
fullscreen:true,
styleHtmlContent:true,
layout:{
xtype:'vbox',
},
scrollable:{
direction:'both',
directionLock:true
},
html:'',
items:[
{
xtype:'toolbar',
docked:'top',
height:40,
items:[
{
xtype:'button',
html:'<img src="./img/arrow_left.png" height="30">', // 방향전환
name:'popLeft'
},
{
xtype:'spacer'
},
{
xtype:'button',
html:'<img src="./img/delete.png" height="20">', // 나가기
name:'popClose'
},
{
xtype:'button',
html:'<img src="./img/minus1.png" height="20">', // 사이즈
name:'popSizeM'
},
{
xtype:'button',
html:'<img src="./img/add.png" height="20">', // 사이즈
name:'popSizeA'
},
{
xtype:'spacer'
},
{
xtype:'button',
html:'<img src="./img/arrow_right.png" height="30">', // 방향전환
name:'popRight'
}]
}],
},
setPage:function(id, subject, content, img, popSize, popRotate, panelWidth)
{
this.galleryid = id;
this.subject = subject;
this.content = content;
this.img = img;
this.popSize = popSize;
this.popRotate = popRotate;
var imgElement = document.createElement("img");
imgElement.src=this.img;
var tempWidth = imgElement.width;
var tempHeight = imgElement.height;
var tempCalc = tempHeight/tempWidth;
imgElement.width = window.screen.width * this.popSize * 0.01;
imgElement.height = imgElement.width * tempCalc;
this.setHtml('<font size=2>' + subject + '</font><BR><img height="' + imgElement.height + 'px" width="' + imgElement.width + 'px" src="' + this.img + '"> ');
this.setImgCls = true;
},
// 이미지 설정
setImg:function()
{
},
// 이미지 해제
releaseImg:function()
{
},
// 초기화
initialize:function(){
this.img='';
this.popSize='';
this.popRotate='';
this.setImgCls = false;
this.flex = 1,
this.layout = {
type: 'vbox',
align:'stretch',
};
this.callParent();
}
});
이제 가장중요한 controller입니다......
GalleryDetailController.js 파일입니다... 소스에 간단한 설명을 해놓았으니 잘 살펴보시기 바랍니다.....
Ext.define('Gallery.controller.GalleryDetailController', {
extend: 'Ext.app.Controller',
xtype:'gallerydetailcontroller',
name:'GalleryDetailController',
requires:[
'Ext.Ajax',
'Ext.Anim',
'Gallery.view.GalleryDetailCard',
'Gallery.common.GalleryData'
],
config: {
// 참조개체를 정의한다.
refs: {
galleryListView: 'gallerylistview',
galleryDetailView: 'gallerydetailview',
galleryDetailCard: 'gallerydetailcard',
galleryDetailCardPop: 'gallerydetailcardpop',
galleryDetailCarousel: 'gallerydetailview [name=gallerydetailcarousel]',
subjectToolbar : 'gallerydetailview [name=subjectToolbar]',
backList : 'gallerydetailview [name=backList]',
chgSize: 'gallerydetailview [name=chgSize]',
popLeft: 'gallerydetailcardpop [name=popLeft]',
popClose: 'gallerydetailcardpop [name=popClose]',
popSizeA: 'gallerydetailcardpop [name=popSizeA]',
popSizeM: 'gallerydetailcardpop [name=popSizeM]',
popRotate: 'gallerydetailcardpop [name=popRotate]',
popRight: 'gallerydetailcardpop [name=popRight]',
},
// 참조개체의 이벤트를 정의함.
control: {
// viewport로부터 화면의 가로세로 변환을 감지하여 이벤트를 처리함.
viewport:{
orientationchange: 'onOrien'
},
galleryDetailCarousel: {
activeitemchange: 'onCarouselChange'
},
backList:{
tap:'onBackList'
},
chgSize:{
tap:'onChgSize'
},
popLeft:{
tap:'onPopLeft'
},
popClose:{
tap:'onPopClose'
},
popSizeA:{
tap:'onPopSizeA'
},
popSizeM:{
tap:'onPopSizeM'
},
popRotate:{
tap:'onPopRotate'
},
popRight:{
tap:'onPopRight'
},
}
},
// 멤버변수
currPageNum:0,
carouselAdded:0,
imgDraw:false,
panelPop:'',
popState:0,
launch: function() {
},
// 가로세로가 변경될 경우 시간을 지연한다.
onOrien:function(viewport, orientation, width, height){
if(orientation == 'portrait')
{
var strtTime = new Date().getTime();
for(var i=0;i<10000; i++)
{
var endTime= new Date().getTime();
if((endTime - strtTime) > 500)
{
break;
}
}
}
},
// 파일목록에서 상세화면이 호출될때 메소드
setPage:function(cpage){
this.currPageNum = cpage;
this.setDataPos('first');
},
// 폰갭플러그인을 통해 목록을 가져옴.
callServer:function(inputPage)
{
var tempThis= this;
var startNum = (inputPage-1)* 10;
var lastNum = startNum + 10;
if(startNum > Gallery.common.GalleryData.totData.length)
{
this.currPageNum = this.currPageNum - 1;
alert('더이상 데이터가 없습니다.');
return;
}
if( Gallery.common.GalleryData.totData.length < lastNum )
{
lastNum = Gallery.common.GalleryData.totData.length;
}
var tempArray = Array (lastNum-startNum);
var j=0;
for(i = startNum; i< lastNum; i++)
{
tempArray[j] = Gallery.common.GalleryData.totData[i];
j++;
}
this.addProxyData(tempArray);
},
// 상세화면관련====================================
// 앞화면(리스트 조회에서) 클릭하였을 경우 보여주는 현재 화면의 위치
setDataPos:function(val)
{
if(val=='first')
{
for(i= this.getGalleryDetailCarousel().getItems().length-1; i >= this.carouselAdded;i--)
{
this.getGalleryDetailCarousel().removeAt(i);
}
}
var start_i = Gallery.common.GalleryData.minDataPos;
if(start_i< 0)
start_i=0;
for(i = start_i; i< Gallery.common.GalleryData.maxDataPos;i++)
{
try{ this.addArt(Gallery.common.GalleryData.orgData[i]); }catch(e){ console.log('오류무시'); }
}
this.getGalleryDetailCarousel().setActiveItem( Gallery.common.GalleryData.curDataPos - start_i);
this.getGalleryDetailView().imgDraw = true;
// 첫번째 호출일경우
if(val=='first')
{
console.log('첫번째위치 ');
var firstPos = Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos;
if(firstPos < 0)
firstPos = 0;
var detailCard = this.getGalleryDetailCarousel().getAt(firstPos + this.carouselAdded);
this.getSubjectToolbar().setTitle(detailCard.subject);
try
{
Gallery.common.GalleryData.curId = detailCard.galleryid;
}
catch(e){}
}
},
// 가져온 데이터받기이벤트
addProxyData:function(result)
{
if(result == null){
}
else
{
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
this.getGalleryDetailCarousel().removeAt(0 + this.carouselAdded);
}
}
this.addProxyDataSub(result);
}
},
// addProxyData로부터 호출됨
addProxyDataSub:function(result)
{
var temp = Gallery.common.GalleryData.maxDataPos;
for(i = 0; i< result.length; i++)
{
Gallery.common.GalleryData.orgData.push(result[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos + 10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos - 30;
if(Gallery.common.GalleryData.maxDataPos > Gallery.common.GalleryData.totDataPos)
{
Gallery.common.GalleryData.totDataPos = Gallery.common.GalleryData.maxDataPos;
}
for(i = 0; i< result.length; i++)
{
this.addArt(result[i]);
}
if(temp >= 30)
{
this.getGalleryDetailCarousel().setActiveItem(19);
}
},
// 데이터를 추가함
addData:function(result)
{
for(i = 0; i< result.length; i++)
{
this.addArt(result[i]);
}
},
// 데이터를 삽입함
insertData:function(result)
{
for(i = 9; i>=0; i--)
{
this.insertArt(result[i]);
}
},
// 커로우절화면====================================
onCarouselChange:function( a, index1,index2){
console.log('움직였다.' + index1 + "." + index2);
if(this.getGalleryDetailView().imgDraw == true)
{
// 화면갱신
var curIndex = Number(this.getGalleryDetailCarousel().getActiveIndex());
{
{
// 페이지가 움직일때 Title설정
var detailCard =
this.getGalleryDetailCarousel().getAt(curIndex+this.carouselAdded);
Gallery.common.GalleryData.curId = detailCard.galleryid;
// 타이틀바 설정 (적절히 크기 등 수정요함)
this.getSubjectToolbar().setTitle(detailCard.subject);
}
}
// 오른쪽으로 이동
if(curIndex == this.getGalleryDetailCarousel().getItems().length-1-this.carouselAdded)
{
// 현재 MAX값보다 큰 값을 가져올 경우 서버로부터 데이터를 요청함.
if(Gallery.common.GalleryData.maxDataPos >= Gallery.common.GalleryData.totDataPos)
{
this.currPageNum = this.currPageNum+1;
this.callServer(this.currPageNum);
}
else
{
// 현재위치보다 작고 30건 이상일 경우 이미 불러온 10건을 리스트에 추가함.
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
this.getGalleryDetailCarousel().removeAt(0 + this.carouselAdded);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos;
i< Gallery.common.GalleryData.maxDataPos+10;
i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos+10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
this.addData(result);
}
}
}
else if(curIndex == 0)
{
// 맨 왼쪽으로 왔을 경우
console.log("왼쪽으로 이동");
if(Gallery.common.GalleryData.maxDataPos > 30)
{
// 30건 이상이 있을 경우 오른쪽 10건을 지우고 왼쪽 10건을 추가함.
for(i=9; i>=0;i--)
{
this.getGalleryDetailCarousel().removeAt(i + 20 + this.carouselAdded);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos-40;
i< Gallery.common.GalleryData.maxDataPos-30;
i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos-10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
this.insertData(result);
this.getGalleryDetailCarousel().setActiveItem(10);
}
}
}
if(this.popState == 1)
{
this.pageRefresh();
}
},
// 앞화면(리스트 조회에서) 클릭하였을 경우 보여주는 현재 화면의 위치
setDetailDataPos:function(val)
{
if(val=='first')
{
for(i=this.getGalleryDetailCarousel().getItems().length-1; i>=this.carouselAdded;i--)
{
this.getGalleryDetailCarousel().removeAt(i);
}
}
var start_i = Gallery.common.GalleryData.minDataPos;
if(start_i< 0)
start_i=0;
for(i = start_i; i< Gallery.common.GalleryData.maxDataPos;i++)
{
try{ this.addArt(Gallery.common.GalleryData.orgData[i]); }catch(e){}
}
// 페이지를 이동시킨다.
this.getGalleryDetailCarousel().setActiveItem( Gallery.common.GalleryData.curDataPos - start_i);
this.getGalleryDetailView().imgDraw = true;
// 첫번째 호출일경우
if(val=='first')
{
var firstPos = Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos;
if(firstPos < 0)
firstPos = 0;
var detailCard = this.getGalleryDetailCarousel().getAt(firstPos+this.carouselAdded);
try
{
Gallery.common.GalleryData.curId = detailCard.galleryid;
}
catch(e){ console.log('에러무시' ); }
}
},
// GalleryDetailCard에 이미지를 넣은뒤 Carousel에 추가함
addArt:function(photodata){
var detailCard = new Ext.create('Gallery.view.GalleryDetailCard');
detailCard.setPage( photodata.id,
photodata.subject,
photodata.content,
photodata.img);
this.getGalleryDetailCarousel().add(detailCard);
},
// 앞쪽에 CardDetailCard를 추가함
insertArt:function(photodata) {
var detailCard = new Ext.create('Gallery.view.GalleryDetailCard');
detailCard.setPage( photodata.id,
photodata.subject,
photodata.content,
photodata.img);
this.getGalleryDetailCarousel().insert(0 + this.carouselAdded, detailCard);
},
// 파일목록으로 돌아감.
onBackList:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
this.getGalleryDetailView().hide();
this.getGalleryListView().show();
this.getApplication().getController('GalleryController').returnAddMsg(this.currPageNum);
},
// 상세확대창으로 이동
onChgSize:function()
{
this.getGalleryDetailView().hide();
this.getGalleryDetailCardPop().show();
this.popState = 1;
this.pageRefresh();
},
// 확대창에서 왼쪽이미지로 변경
onPopLeft:function()
{
this.getGalleryDetailCarousel().previous();
},
// 확대창을 닫음
onPopClose:function()
{
this.popState = 0;
this.getGalleryDetailCardPop().hide();
this.getGalleryDetailView().show();
},
// 확대창에서 크기를 늘림
onPopSizeA:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
Gallery.common.GalleryData.popSize = Gallery.common.GalleryData.popSize + 10;
this.pageRefresh();
},
// 확대창에서 크기를 줄임
onPopSizeM:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
Gallery.common.GalleryData.popSize = Gallery.common.GalleryData.popSize - 10;
this.pageRefresh();
},
// 확대창 이미지를 회전시킨 (미사용)
onPopRotate:function()
{
if(Gallery.common.GalleryData.popRotate == "rotate0")
Gallery.common.GalleryData.popRotate = "rotate90";
else if(Gallery.common.GalleryData.popRotate == "rotate90")
Gallery.common.GalleryData.popRotate = "rotate180";
else if(Gallery.common.GalleryData.popRotate == "rotate180")
Gallery.common.GalleryData.popRotate = "rotate270"
else if(Gallery.common.GalleryData.popRotate == "rotate270")
Gallery.common.GalleryData.popRotate = "rotate0";
this.pageRefresh();
},
// 확대창 이미지를 오른쪽 이미지로 대체
onPopRight:function()
{
this.getGalleryDetailCarousel().next();
},
// 확대창의 조작이 있은 후 화면을 갱신함
pageRefresh:function()
{
Gallery.common.GalleryData.curDataPos =
Number(this.getGalleryDetailCarousel().getActiveIndex()) +
Gallery.common.GalleryData.minDataPos;
this.getGalleryDetailCardPop().setPage(
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].id,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].subject,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].content,
Gallery.common.GalleryData.orgData[Gallery.common.GalleryData.curDataPos].img,
Gallery.common.GalleryData.popSize,
Gallery.common.GalleryData.popRotate,
window.screen.width);
}
});
센차터치쪽 소스는 다 보았습니다.... 어떠신지요..... Controller와 Controller간 호출도 살펴보세요...
다음은 폰갭 플러그인을 살펴봐야 할것 같네요.. 계속 4탄으로 이어집니다.
센차터치2 + 폰갭 코믹뷰어 소스공개 2탄
앞글에 이어서 설명합니다...
먼저 센차터치의 소스 부분을 설명하겠습니다...
assets/www폴더를 먼저 보겠습니다... (왜 이곳을 보는지는 아시겠죠...?) 모르시면 책의 앞부분을 다시 살펴보시기 바랍니다.
앞글에서 MVC모델을 올려드렸습니다... style이 조금 들어갔죠... 이미지 처리부분을 만들어주다 보니까...ㅎㅎㅎ...
index.html을 먼저 올려드립니다....----------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>Getting Started</title>
<link rel="stylesheet" href="./touch/resources/css-debug/sencha-touch.css" type="text/css">
<style type="text/css">
.rotate0 {
-webkit-transform:rotate(0deg);
-moz-transform:rotate(0deg);
}
.rotate90 {
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
}
.rotate180 {
-webkit-transform:rotate(180deg);
-moz-transform:rotate(180deg);
}
.rotate270 {
-webkit-transform:rotate(270deg);
-moz-transform:rotate(270deg);
}
</style>
<script type="text/javascript" src="./touch/sencha-touch-debug.js"></script>
<script>
Ext.Loader.setConfig({ disableCaching: false });
Ext.Ajax.setDisableCaching(false);
</script>
<script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>
** app.js를 보겠습니다. 복잡해 보이나요??? 먼저 폰갭을 로딩하기위해 cordova1.8.1.js위치를 설정햇습니다. PhoneGap
으로 설정했네요.... Ext.application에서 model, stores, controller, view를 선언합니다...
view는 좀 분리를 했습니다...
먼저 폴더안의 이미지를 보는 제일 상위를 GalleryDirListView로 선언했구요.. 안의 리스트를 GalleryDirList로 선언했습니다.
클릭해서 나오는 폴더 목록을 GalleryListView로 선언했고 안의 리스트를 GalleryList로 선언했습니다..
상세화면은 GalleryDetailView로 선언했고.. 안의 리스트를 GalleryDetailCard로 선언했으며 이를 컨트롤 하는 Carousel을
GalleryDetailCarousel로선언했으며 확대및 축소 창을 GalleryDetailCardPop으로 선언했습니다....
컨트롤러가 2개지요??? 두 컨트롤러가 상호 동작하게 됩니다.. 컨트롤러가 어떠한 뷰를 담당하는지는 앞글 1탄의 MVC
이미지를 살펴보시기 바랍니다.
app.js 파일입니다. -------------------------------------------------------------------
Ext.Loader.setPath({
'PhoneGap': 'cordova-1.8.1.js'
});
Ext.application({
name: 'Gallery',
models: ['GalleryModel', 'GalleryDirModel'],
stores: ['GalleryStore', 'GalleryDirStore'],
controllers:['GalleryController', 'GalleryDetailController' ],
views: ['GalleryDirListView',
'GalleryDirList',
'GalleryListView',
'GalleryList',
'GalleryDetailView',
'GalleryDetailCard',
'GalleryDetailCarousel',
'GalleryDetailCardPop'],
launch: function() {
var panelDir = Ext.create('Gallery.view.GalleryDirListView');
var panelDirList = Ext.create('Gallery.view.GalleryDirList');
panelDir.setHtml('Analyzing File System ...');
panelDir.add(panelDirList);
Ext.Viewport.add(panelDir);
var panel = Ext.create('Gallery.view.GalleryListView');
var panelList = Ext.create('Gallery.view.GalleryList');
Ext.Viewport.add(panel);
panelList.setStore(Ext.getStore('GalleryStore'));
panel.add(panelList);
panel.hide();
panelDetail = Ext.create('Gallery.view.GalleryDetailView');
Ext.Viewport.add(panelDetail);
panelDetail.hide();
panelDetailPop = Ext.create('Gallery.view.GalleryDetailCardPop');
Ext.Viewport.add(panelDetailPop);
panelDetailPop.hide();
}
});
다음은 각 뷰를 살펴보겠습니다.. 뷰는 화면을 나타내고 로직은 없습니다.. 로직은 Controller로 갔겠죠!!!
GalleryDirListView.js 입니다.------------------------------------
Ext.define("Gallery.view.GalleryDirListView", {
extend: 'Ext.Panel',
xtype:'gallerydirlistview',
fullscreen:true,
config:{
fullscreen: true,
layout:{
type:'vbox',
},
items: [{
xtype: 'toolbar',
docked: 'top',
title:'Sencha Comic Viewer',
}]
}
});
GalleryDirList.js 입니다.------------------------------------
Ext.define("Gallery.view.GalleryDirList", {
extend: 'Ext.List',
xtype:'gallerydirlist',
id:'gallerydirlistid',
config:{
scrollable:true,
flex:1,
onItemDisclosure:false,
itemTpl:'<div><img src="{img0}" height="50" width="50"><img src="{img1}" height="50" width="50"><img src="{img2}" height="50" width="50"><BR><font size="2" color="green">{path}</font></div>',
}
});
GalleryListView.js 파일입니다. ----------------------------------
Ext.define("Gallery.view.GalleryListView", {
extend: 'Ext.Panel',
xtype:'gallerylistview',
fullscreen:true,
config:{
fullscreen: true,
layout:{
type:'vbox',
},
items: [{
xtype: 'toolbar',
docked: 'top',
height:40,
title:'Commic Book',
html:'',
items:[
{
xtype:'button',
name:'backmain',
html:'<img src="./img/home.png" height="25">',
}]
}]
}
});
GalleryList.js파일입니다. ---------------------------------------------------
Ext.define("Gallery.view.GalleryList", {
extend: 'Ext.List',
xtype:'gallerylist',
config:{
scrollable:true,
flex:1,
onItemDisclosure:false,
itemTpl:'<div><img src="{img}" height="50"><font size="2" color="green">{subject}</font></div>',
}
});
3개의 나머지 뷰는 잠시후에 보겠습니다... 이 뷰들을 Controll하는 녀석이 다르기 때문입니다...
GalleryDirModel.js를 살펴보겠습니다. -----------------------------------
모델을 왜 설정하냐면.... 리스트에 나타날 데이터를 정의하였습니다.
원래 이미지를 5개 까지 보여주려고 했거든요.. 실제 풀경로와 파일인지 폴더인지도 구분해야 합니다..
이것은 맨 상위 리스트 에서 사용합니다.
Ext.define('Gallery.model.GalleryDirModel', {
extend: 'Ext.data.Model',
config:{
fields: ['id', 'img0', 'img1', 'img2', 'img3', 'img4','path', 'isFile']
}
});
다음은 GalleryModel.js 입니다. ----------------------------------
이파일은 GalleryListView에서 사용할 리스트의 내용입니다... 이미지와 파일명 등이 있죠...
Ext.define('Gallery.model.GalleryModel', {
extend: 'Ext.data.Model',
config:{
fields: ['id', 'subject', 'content', 'img']
}
});
스토어도 정의해야 하겠죠... ㅎㅎ.. -----------------------------------
역시 폴더리스트와 , 파일리스트에서 사용할 파일들이죠...
GalleryDirStore.js입니다.-------------------------------------
Ext.define('Gallery.store.GalleryDirStore', {
extend : 'Ext.data.Store',
requires: ['Gallery.model.GalleryDirModel'],
config:{
model:'Gallery.model.GalleryDirModel',
autoLoad:true,
}
});
GalleryStore.js -------------------------------------
Ext.define('Gallery.store.GalleryStore', {
extend : 'Ext.data.Store',
requires: ['Gallery.model.GalleryModel'],
config:{
model:'Gallery.model.GalleryModel',
autoLoad:true,
}
});
이제 가장 중요한 Controller로 넘어가겠습니다.... 아!.. 그전에 Common 파일을 살펴보겠습니다.
MVC에 포함되지 않죠.. 어떻게 정의했냐면...app.js와 controller를 살펴보세요...
GalleryData.js
Ext.define("Gallery.common.GalleryData",{
singleton: true,
totDataPos:0,
maxDataPos:0,
minDataPos:0,
curDataPos:0,
curId:'0',
curSubject:'',
curContent:'',
curImg:'',
orgData:new Array(0),
totData:new Array(0),
popRotate:'rotate0',
popSize: 100,
});
정말 Controller입니다. ----------------------------------------------
소스를 잘 살펴보세요... 깁~~~ 니다.
GalleryController.js 파일입니다.
Ext.define('Gallery.controller.GalleryController', {
extend: 'Ext.app.Controller',
// Gallery.common.GalleryData는 model,view, controller에 포함되지 않으므로
// 별도로 추가함
requires:[
'PhoneGap',
'Ext.Ajax',
'Ext.scroll.Scroller',
'Gallery.common.GalleryData',
],
config: {
// 참조개체정의
refs: {
galleryDirListView: 'gallerydirlistview',
galleryDirList: 'gallerydirlist',
galleryListView: 'gallerylistview',
galleryList: 'gallerylist',
galleryDetailView: 'gallerydetailview',
backMain: 'gallerylistview [name=backmain]',
},
// 개체별 이벤트를 정의
control: {
viewport:{
orientationchange: 'onOrien'
},
galleryList: {
itemtap: 'onItemTap'
},
galleryDirList: {
itemtap: 'onItemTapDir'
},
backMain: {
tap:'onBackMain'
}
}
},
itemHeight:0,
currPageNum:1,
maxPos:0,
Scroller:'listScroller',
launch: function() {
listScroller = this.getGalleryList().getScrollable().getScroller();
listScroller.on('scrollend', this.addScrollAfter, this);
listScroller.on('maxpositionchange', this.chgMaxPos, this);
me = this;
this.startPhoneGap();
},
// 갸로세로 방향이 바뀔때 호출됨 시간을 조금 늘림.
onOrien:function(viewport, orientation, width, height){
if(orientation == 'portrait')
{
var strtTime = new Date().getTime();
for(var i=0;i<10000; i++)
{
var endTime= new Date().getTime();
if((endTime - strtTime) > 500)
{
break;
}
}
}
},
callDirList:function()
{
},
callServerTot:function(inputPath)
{
window.plugins.ExecFile.searchFile('', inputPath);
},
callServer:function(inputPage)
{
var tempThis= this;
var startNum = (inputPage-1)* 10;
var lastNum = startNum + 10;
if(startNum > Gallery.common.GalleryData.totData.length)
{
this.currPageNum = this.currPageNum - 1;
alert('더이상 데이터가 없습니다.');
return;
}
if( Gallery.common.GalleryData.totData.length < lastNum )
{
lastNum = Gallery.common.GalleryData.totData.length;
}
var tempArray = Array (lastNum-startNum);
var j=0;
for(i = startNum; i< lastNum; i++)
{
tempArray[j] = Gallery.common.GalleryData.totData[i];
j++;
}
console.log("tempArray:" + tempArray);
this.addProxyData(tempArray);
},
// 리스트패널 관련==================================
addProxyData:function(result)
{
console.log("addProxyData----------------");
console.log(result);
if(result == null)
{
// 마지막 페이지를 서버에서 null로 줌.
}
else
{
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
Ext.getStore('GalleryStore').removeAt(0);
}
}
setTimeout(this.addProxyDataSub(result), 500);
}
},
addProxyDataSub:function(result)
{
console.log('addProxyDataSub-----------------------' + result.length);
console.log(result);
for(i = 0; i< result.length; i++)
{
Gallery.common.GalleryData.orgData.push(result[i]);
}
console.log("1:" + result);
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos + 10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos - 30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
if(Gallery.common.GalleryData.maxDataPos > Gallery.common.GalleryData.totDataPos)
{
Gallery.common.GalleryData.totDataPos = Gallery.common.GalleryData.maxDataPos;
}
console.log("2:" + result);
Ext.getStore('GalleryStore').add(result);
// 서버로부터 데이터를 받았을경우 데이터리스트가 가지고 있는 이미지 크기를 계산함(처음 한번만)
if(this.itemHeight == 0)
{
try{ itemHeight = this.getGalleryList().element.down('.x-list-item').getHeight(); }catch(e){}
}
// 스크롤이 원위치로 찾아감(10건을 추가하였으니 반대로 10건 위로 올라감)
if( Gallery.common.GalleryData.maxDataPos> 30)
{
listScroller.scrollBy(0,itemHeight * (-10) );
}
this.getGalleryList().setStore(Ext.getStore('GalleryStore'));
},
// 리스트 뒤에 데이터를 추가함.
addData:function(result)
{
Ext.getStore('GalleryStore').add(result);
if( Gallery.common.GalleryData.maxDataPos> 30)
{
listScroller.scrollBy(0,itemHeight * (-10) );
}
},
// 리스트 앞에 데이터를 삽입함
insertData:function(result)
{
// 위로 올릴경우는 insert로 처리함
Ext.getStore('GalleryStore').insert(0,result);
listScroller.scrollBy(0,itemHeight * 10 );
},
// 상세화면에서 리턴되었을때 화면을 갱신함.
returnAddMsg:function(cpage)
{
this.currPageNum = cpage;
Ext.getStore('GalleryStore').removeAll();
for(i=Gallery.common.GalleryData.minDataPos; i< Gallery.common.GalleryData.maxDataPos; i++)
{
Ext.getStore('GalleryStore').add(Gallery.common.GalleryData.orgData[i]);
}
listScroller.scrollTo(0,itemHeight * Math.floor( (Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos-1)) );
},
// 리스트관련 ====================================
addScrollAfter:function(a,b,c)
{
console.log('addScroller');
// 아래로 이동
if(c >= this.maxPos)
{
console.log("아래로 이동");
// 제일 하단보다 더 밑으로 내릴 경우 서버로 부터데이터를가져옴
if(Gallery.common.GalleryData.maxDataPos >= Gallery.common.GalleryData.totDataPos)
{
this.currPageNum = this.currPageNum + 1;
this.callServer(this.currPageNum);
}
else
{
console.log('그냥하단' + Gallery.common.GalleryData.maxDataPos);
// 제일 아래가 아닐 경우 기존 데이터를 사용하여 30건만 유지함
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
Ext.getStore('GalleryStore').removeAt(0);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos; i< Gallery.common.GalleryData.maxDataPos+10;i++)
{
if(Gallery.common.GalleryData.orgData[i] != null)
{
try{result.push(Gallery.common.GalleryData.orgData[i]); }catch(e){}
}
else
{
console.log('데이터 없음');
}
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos+10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
this.addData(result);
}
}
}
else if(c == 0 && Gallery.common.GalleryData.maxDataPos >30) // 위로이동
{
console.log('위로이동' + Gallery.common.GalleryData.maxDataPos);
for(i=30-1; i>=20;i--)
{
try{Ext.getStore('GalleryStore').removeAt(i); } catch(e){}
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos-40; i< Gallery.common.GalleryData.maxDataPos-30;i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos-10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
this.insertData(result);
}
},
// 스크롤러에 의해 위치가 바뀌었다.
chgMaxPos:function(a,b,c)
{
console.log('chgMaxPos');
this.maxPos = b.y;
},
// 파일 리스트의 아이템이 클릭됨
onItemTap:function(list,index, item){
Gallery.common.GalleryData.curDataPos = index + Gallery.common.GalleryData.minDataPos;
this.getGalleryListView().hide();
this.getGalleryDetailView().destroy();
panelDetail = Ext.create('Gallery.view.GalleryDetailView');
this.getGalleryDetailView().show();
this.getApplication().getController('GalleryDetailController').setPage(this.currPageNum);
},
// 폴더 리스트이 아이템이 클릭됨
onItemTapDir:function(list,index, item){
this.initGalleryList();
temp = Ext.getStore('GalleryDirStore').data.items[index].data.path;
// 해당 폴더로 이동하여 GalleryList를 보여준다.
this.getGalleryDirListView().hide();
this.getGalleryListView().setHtml('<font size=2>' + temp + '</font>');
this.getGalleryListView().show();
this.callServerTot(temp);
},
// 파일리스트를 초기화 시켜줌
initGalleryList:function()
{
this.currPageNum = 1;
Ext.getStore('GalleryStore').removeAll();
Gallery.common.GalleryData.totDataPos=0;
Gallery.common.GalleryData.maxDataPos=0;
Gallery.common.GalleryData.minDataPos=0;
Gallery.common.GalleryData.curDataPos=0;
Gallery.common.GalleryData.curId='0';
Gallery.common.GalleryData.curSubject='';
Gallery.common.GalleryData.curContent='';
Gallery.common.GalleryData.curImg='';
Gallery.common.GalleryData.orgData = new Array(0);
Gallery.common.GalleryData.totData = new Array(0);
},
// 폴더리스트로 이동함
onBackMain:function()
{
this.getGalleryListView().hide();
this.getGalleryDirListView().show();
},
// PhoneGap ---------------------------------
successRootSystem:function(directoryEntry){
dirEntry=directoryEntry;
var rootPath = dirEntry.fullPath;
window.plugins.ExecFile.searchDir('', rootPath);
},
failFileSystem:function(error){
alert('error:' + error.code);
file.releaseMask();
},
getRootDir:function( )
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem){
root= fileSystem.root;
me.successRootSystem(root);
},
function(evt){
alert('file read error!! : ' + evt.target.error.code);
console.log(">>>>" + evt.target.error.code);
//file.releaseMask();
}
);
},
onDeviceReady:function() {
document.addEventListener("menubutton", me.onMenuButton, false);
document.addEventListener("backbutton", me.onBackButton, false);
me.setPlugIn();
me.getRootDir();
},
onMenuButton:function(){
if(confirm('Exit?')== true)
{
navigator.app.exitApp();
}
},
onBackButton:function(){
if(confirm('Exit?')== true)
{
navigator.app.exitApp();
}
},
startPhoneGap:function()
{
document.addEventListener("deviceready", me.onDeviceReady, false);
},
setPlugIn:function()
{
ExecFile = function() {
};
ExecFile.getMe = function()
{
return me;
}
ExecFile.install = function(){
return window.plugins.ExecFile;
};
ExecFile.prototype._onError = function(data) {
if (typeof window.plugins.execfile.onError === "function") {
window.plugins.childBrowser.onError(data);
}
};
ExecFile.prototype.exec = function(url, options) {
cordova.exec( '', '', "ExecFile", "exec", [url, options]);
};
ExecFile.onPackageList = function(data) {
storePackageList.setData(Ext.decode(data));
Ext.getCmp('packagelist').setStore(storePackageList);
storePackageList.load();
};
ExecFile.prototype.getPackageList = function(url, options) {
cordova.exec( ExecFile.onPackageList, '', "ExecFile", "getPackageList", [url, options]);
};
ExecFile.onSearchList = function(data) {
var temp = Ext.decode(data);
for(i=0; i<temp.length;i++)
{
Gallery.common.GalleryData.totData.push(temp[i]);
}
ExecFile.getMe().callServer(1);
};
ExecFile.prototype.searchFile = function(url, options) {
cordova.exec( ExecFile.onSearchList, '', "ExecFile", "searchFile", [url, options]);
};
ExecFile.onSearchDir = function(data) {
me.getGalleryDirListView().setHtml('');
Ext.getStore('GalleryDirStore').setData(Ext.decode(data));
//storeSearchList.setData(Ext.decode(data));
Ext.getStore('GalleryDirStore').load();
ExecFile.getMe().getGalleryDirList().setStore(Ext.getStore('GalleryDirStore'));
};
ExecFile.prototype.searchDir = function(url, options) {
cordova.exec( ExecFile.onSearchDir, '', "ExecFile", "searchDir", [url, options]);
};
cordova.addConstructor(function() {
cordova.addPlugin("ExecFile", new ExecFile());
});
}
});
Controller는 주석을 달아놓았으므로 잘 해석해보세요... 이중 cordova의 기능을 사용하는데 이부분은 안드로이드 앱에서 데이터를 가져오는 부분으로 생각하세요.... 이 부분은 4탄이나 5탄쯤 설명해야 할것 같습니다.
다시 3탄으로 이어집니다. 상세화면을 설명해야죠....
먼저 센차터치의 소스 부분을 설명하겠습니다...
assets/www폴더를 먼저 보겠습니다... (왜 이곳을 보는지는 아시겠죠...?) 모르시면 책의 앞부분을 다시 살펴보시기 바랍니다.
앞글에서 MVC모델을 올려드렸습니다... style이 조금 들어갔죠... 이미지 처리부분을 만들어주다 보니까...ㅎㅎㅎ...
index.html을 먼저 올려드립니다....----------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>Getting Started</title>
<link rel="stylesheet" href="./touch/resources/css-debug/sencha-touch.css" type="text/css">
<style type="text/css">
.rotate0 {
-webkit-transform:rotate(0deg);
-moz-transform:rotate(0deg);
}
.rotate90 {
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
}
.rotate180 {
-webkit-transform:rotate(180deg);
-moz-transform:rotate(180deg);
}
.rotate270 {
-webkit-transform:rotate(270deg);
-moz-transform:rotate(270deg);
}
</style>
<script type="text/javascript" src="./touch/sencha-touch-debug.js"></script>
<script>
Ext.Loader.setConfig({ disableCaching: false });
Ext.Ajax.setDisableCaching(false);
</script>
<script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>
** app.js를 보겠습니다. 복잡해 보이나요??? 먼저 폰갭을 로딩하기위해 cordova1.8.1.js위치를 설정햇습니다. PhoneGap
으로 설정했네요.... Ext.application에서 model, stores, controller, view를 선언합니다...
view는 좀 분리를 했습니다...
먼저 폴더안의 이미지를 보는 제일 상위를 GalleryDirListView로 선언했구요.. 안의 리스트를 GalleryDirList로 선언했습니다.
클릭해서 나오는 폴더 목록을 GalleryListView로 선언했고 안의 리스트를 GalleryList로 선언했습니다..
상세화면은 GalleryDetailView로 선언했고.. 안의 리스트를 GalleryDetailCard로 선언했으며 이를 컨트롤 하는 Carousel을
GalleryDetailCarousel로선언했으며 확대및 축소 창을 GalleryDetailCardPop으로 선언했습니다....
컨트롤러가 2개지요??? 두 컨트롤러가 상호 동작하게 됩니다.. 컨트롤러가 어떠한 뷰를 담당하는지는 앞글 1탄의 MVC
이미지를 살펴보시기 바랍니다.
app.js 파일입니다. -------------------------------------------------------------------
Ext.Loader.setPath({
'PhoneGap': 'cordova-1.8.1.js'
});
Ext.application({
name: 'Gallery',
models: ['GalleryModel', 'GalleryDirModel'],
stores: ['GalleryStore', 'GalleryDirStore'],
controllers:['GalleryController', 'GalleryDetailController' ],
views: ['GalleryDirListView',
'GalleryDirList',
'GalleryListView',
'GalleryList',
'GalleryDetailView',
'GalleryDetailCard',
'GalleryDetailCarousel',
'GalleryDetailCardPop'],
launch: function() {
var panelDir = Ext.create('Gallery.view.GalleryDirListView');
var panelDirList = Ext.create('Gallery.view.GalleryDirList');
panelDir.setHtml('Analyzing File System ...');
panelDir.add(panelDirList);
Ext.Viewport.add(panelDir);
var panel = Ext.create('Gallery.view.GalleryListView');
var panelList = Ext.create('Gallery.view.GalleryList');
Ext.Viewport.add(panel);
panelList.setStore(Ext.getStore('GalleryStore'));
panel.add(panelList);
panel.hide();
panelDetail = Ext.create('Gallery.view.GalleryDetailView');
Ext.Viewport.add(panelDetail);
panelDetail.hide();
panelDetailPop = Ext.create('Gallery.view.GalleryDetailCardPop');
Ext.Viewport.add(panelDetailPop);
panelDetailPop.hide();
}
});
다음은 각 뷰를 살펴보겠습니다.. 뷰는 화면을 나타내고 로직은 없습니다.. 로직은 Controller로 갔겠죠!!!
GalleryDirListView.js 입니다.------------------------------------
Ext.define("Gallery.view.GalleryDirListView", {
extend: 'Ext.Panel',
xtype:'gallerydirlistview',
fullscreen:true,
config:{
fullscreen: true,
layout:{
type:'vbox',
},
items: [{
xtype: 'toolbar',
docked: 'top',
title:'Sencha Comic Viewer',
}]
}
});
GalleryDirList.js 입니다.------------------------------------
Ext.define("Gallery.view.GalleryDirList", {
extend: 'Ext.List',
xtype:'gallerydirlist',
id:'gallerydirlistid',
config:{
scrollable:true,
flex:1,
onItemDisclosure:false,
itemTpl:'<div><img src="{img0}" height="50" width="50"><img src="{img1}" height="50" width="50"><img src="{img2}" height="50" width="50"><BR><font size="2" color="green">{path}</font></div>',
}
});
GalleryListView.js 파일입니다. ----------------------------------
Ext.define("Gallery.view.GalleryListView", {
extend: 'Ext.Panel',
xtype:'gallerylistview',
fullscreen:true,
config:{
fullscreen: true,
layout:{
type:'vbox',
},
items: [{
xtype: 'toolbar',
docked: 'top',
height:40,
title:'Commic Book',
html:'',
items:[
{
xtype:'button',
name:'backmain',
html:'<img src="./img/home.png" height="25">',
}]
}]
}
});
GalleryList.js파일입니다. ---------------------------------------------------
Ext.define("Gallery.view.GalleryList", {
extend: 'Ext.List',
xtype:'gallerylist',
config:{
scrollable:true,
flex:1,
onItemDisclosure:false,
itemTpl:'<div><img src="{img}" height="50"><font size="2" color="green">{subject}</font></div>',
}
});
3개의 나머지 뷰는 잠시후에 보겠습니다... 이 뷰들을 Controll하는 녀석이 다르기 때문입니다...
GalleryDirModel.js를 살펴보겠습니다. -----------------------------------
모델을 왜 설정하냐면.... 리스트에 나타날 데이터를 정의하였습니다.
원래 이미지를 5개 까지 보여주려고 했거든요.. 실제 풀경로와 파일인지 폴더인지도 구분해야 합니다..
이것은 맨 상위 리스트 에서 사용합니다.
Ext.define('Gallery.model.GalleryDirModel', {
extend: 'Ext.data.Model',
config:{
fields: ['id', 'img0', 'img1', 'img2', 'img3', 'img4','path', 'isFile']
}
});
다음은 GalleryModel.js 입니다. ----------------------------------
이파일은 GalleryListView에서 사용할 리스트의 내용입니다... 이미지와 파일명 등이 있죠...
Ext.define('Gallery.model.GalleryModel', {
extend: 'Ext.data.Model',
config:{
fields: ['id', 'subject', 'content', 'img']
}
});
스토어도 정의해야 하겠죠... ㅎㅎ.. -----------------------------------
역시 폴더리스트와 , 파일리스트에서 사용할 파일들이죠...
GalleryDirStore.js입니다.-------------------------------------
Ext.define('Gallery.store.GalleryDirStore', {
extend : 'Ext.data.Store',
requires: ['Gallery.model.GalleryDirModel'],
config:{
model:'Gallery.model.GalleryDirModel',
autoLoad:true,
}
});
GalleryStore.js -------------------------------------
Ext.define('Gallery.store.GalleryStore', {
extend : 'Ext.data.Store',
requires: ['Gallery.model.GalleryModel'],
config:{
model:'Gallery.model.GalleryModel',
autoLoad:true,
}
});
이제 가장 중요한 Controller로 넘어가겠습니다.... 아!.. 그전에 Common 파일을 살펴보겠습니다.
MVC에 포함되지 않죠.. 어떻게 정의했냐면...app.js와 controller를 살펴보세요...
GalleryData.js
Ext.define("Gallery.common.GalleryData",{
singleton: true,
totDataPos:0,
maxDataPos:0,
minDataPos:0,
curDataPos:0,
curId:'0',
curSubject:'',
curContent:'',
curImg:'',
orgData:new Array(0),
totData:new Array(0),
popRotate:'rotate0',
popSize: 100,
});
정말 Controller입니다. ----------------------------------------------
소스를 잘 살펴보세요... 깁~~~ 니다.
GalleryController.js 파일입니다.
Ext.define('Gallery.controller.GalleryController', {
extend: 'Ext.app.Controller',
// Gallery.common.GalleryData는 model,view, controller에 포함되지 않으므로
// 별도로 추가함
requires:[
'PhoneGap',
'Ext.Ajax',
'Ext.scroll.Scroller',
'Gallery.common.GalleryData',
],
config: {
// 참조개체정의
refs: {
galleryDirListView: 'gallerydirlistview',
galleryDirList: 'gallerydirlist',
galleryListView: 'gallerylistview',
galleryList: 'gallerylist',
galleryDetailView: 'gallerydetailview',
backMain: 'gallerylistview [name=backmain]',
},
// 개체별 이벤트를 정의
control: {
viewport:{
orientationchange: 'onOrien'
},
galleryList: {
itemtap: 'onItemTap'
},
galleryDirList: {
itemtap: 'onItemTapDir'
},
backMain: {
tap:'onBackMain'
}
}
},
itemHeight:0,
currPageNum:1,
maxPos:0,
Scroller:'listScroller',
launch: function() {
listScroller = this.getGalleryList().getScrollable().getScroller();
listScroller.on('scrollend', this.addScrollAfter, this);
listScroller.on('maxpositionchange', this.chgMaxPos, this);
me = this;
this.startPhoneGap();
},
// 갸로세로 방향이 바뀔때 호출됨 시간을 조금 늘림.
onOrien:function(viewport, orientation, width, height){
if(orientation == 'portrait')
{
var strtTime = new Date().getTime();
for(var i=0;i<10000; i++)
{
var endTime= new Date().getTime();
if((endTime - strtTime) > 500)
{
break;
}
}
}
},
callDirList:function()
{
},
callServerTot:function(inputPath)
{
window.plugins.ExecFile.searchFile('', inputPath);
},
callServer:function(inputPage)
{
var tempThis= this;
var startNum = (inputPage-1)* 10;
var lastNum = startNum + 10;
if(startNum > Gallery.common.GalleryData.totData.length)
{
this.currPageNum = this.currPageNum - 1;
alert('더이상 데이터가 없습니다.');
return;
}
if( Gallery.common.GalleryData.totData.length < lastNum )
{
lastNum = Gallery.common.GalleryData.totData.length;
}
var tempArray = Array (lastNum-startNum);
var j=0;
for(i = startNum; i< lastNum; i++)
{
tempArray[j] = Gallery.common.GalleryData.totData[i];
j++;
}
console.log("tempArray:" + tempArray);
this.addProxyData(tempArray);
},
// 리스트패널 관련==================================
addProxyData:function(result)
{
console.log("addProxyData----------------");
console.log(result);
if(result == null)
{
// 마지막 페이지를 서버에서 null로 줌.
}
else
{
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
Ext.getStore('GalleryStore').removeAt(0);
}
}
setTimeout(this.addProxyDataSub(result), 500);
}
},
addProxyDataSub:function(result)
{
console.log('addProxyDataSub-----------------------' + result.length);
console.log(result);
for(i = 0; i< result.length; i++)
{
Gallery.common.GalleryData.orgData.push(result[i]);
}
console.log("1:" + result);
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos + 10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos - 30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
if(Gallery.common.GalleryData.maxDataPos > Gallery.common.GalleryData.totDataPos)
{
Gallery.common.GalleryData.totDataPos = Gallery.common.GalleryData.maxDataPos;
}
console.log("2:" + result);
Ext.getStore('GalleryStore').add(result);
// 서버로부터 데이터를 받았을경우 데이터리스트가 가지고 있는 이미지 크기를 계산함(처음 한번만)
if(this.itemHeight == 0)
{
try{ itemHeight = this.getGalleryList().element.down('.x-list-item').getHeight(); }catch(e){}
}
// 스크롤이 원위치로 찾아감(10건을 추가하였으니 반대로 10건 위로 올라감)
if( Gallery.common.GalleryData.maxDataPos> 30)
{
listScroller.scrollBy(0,itemHeight * (-10) );
}
this.getGalleryList().setStore(Ext.getStore('GalleryStore'));
},
// 리스트 뒤에 데이터를 추가함.
addData:function(result)
{
Ext.getStore('GalleryStore').add(result);
if( Gallery.common.GalleryData.maxDataPos> 30)
{
listScroller.scrollBy(0,itemHeight * (-10) );
}
},
// 리스트 앞에 데이터를 삽입함
insertData:function(result)
{
// 위로 올릴경우는 insert로 처리함
Ext.getStore('GalleryStore').insert(0,result);
listScroller.scrollBy(0,itemHeight * 10 );
},
// 상세화면에서 리턴되었을때 화면을 갱신함.
returnAddMsg:function(cpage)
{
this.currPageNum = cpage;
Ext.getStore('GalleryStore').removeAll();
for(i=Gallery.common.GalleryData.minDataPos; i< Gallery.common.GalleryData.maxDataPos; i++)
{
Ext.getStore('GalleryStore').add(Gallery.common.GalleryData.orgData[i]);
}
listScroller.scrollTo(0,itemHeight * Math.floor( (Gallery.common.GalleryData.curDataPos - Gallery.common.GalleryData.minDataPos-1)) );
},
// 리스트관련 ====================================
addScrollAfter:function(a,b,c)
{
console.log('addScroller');
// 아래로 이동
if(c >= this.maxPos)
{
console.log("아래로 이동");
// 제일 하단보다 더 밑으로 내릴 경우 서버로 부터데이터를가져옴
if(Gallery.common.GalleryData.maxDataPos >= Gallery.common.GalleryData.totDataPos)
{
this.currPageNum = this.currPageNum + 1;
this.callServer(this.currPageNum);
}
else
{
console.log('그냥하단' + Gallery.common.GalleryData.maxDataPos);
// 제일 아래가 아닐 경우 기존 데이터를 사용하여 30건만 유지함
if( Gallery.common.GalleryData.maxDataPos>= 30)
{
for(i=0;i<10;i++)
{
Ext.getStore('GalleryStore').removeAt(0);
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos; i< Gallery.common.GalleryData.maxDataPos+10;i++)
{
if(Gallery.common.GalleryData.orgData[i] != null)
{
try{result.push(Gallery.common.GalleryData.orgData[i]); }catch(e){}
}
else
{
console.log('데이터 없음');
}
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos+10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
this.addData(result);
}
}
}
else if(c == 0 && Gallery.common.GalleryData.maxDataPos >30) // 위로이동
{
console.log('위로이동' + Gallery.common.GalleryData.maxDataPos);
for(i=30-1; i>=20;i--)
{
try{Ext.getStore('GalleryStore').removeAt(i); } catch(e){}
}
var result = new Array(0);
for(i= Gallery.common.GalleryData.maxDataPos-40; i< Gallery.common.GalleryData.maxDataPos-30;i++)
{
result.push(Gallery.common.GalleryData.orgData[i]);
}
Gallery.common.GalleryData.maxDataPos = Gallery.common.GalleryData.maxDataPos-10;
Gallery.common.GalleryData.minDataPos = Gallery.common.GalleryData.maxDataPos-30;
if(Gallery.common.GalleryData.minDataPos < 0)
{
Gallery.common.GalleryData.minDataPos = 0;
}
this.insertData(result);
}
},
// 스크롤러에 의해 위치가 바뀌었다.
chgMaxPos:function(a,b,c)
{
console.log('chgMaxPos');
this.maxPos = b.y;
},
// 파일 리스트의 아이템이 클릭됨
onItemTap:function(list,index, item){
Gallery.common.GalleryData.curDataPos = index + Gallery.common.GalleryData.minDataPos;
this.getGalleryListView().hide();
this.getGalleryDetailView().destroy();
panelDetail = Ext.create('Gallery.view.GalleryDetailView');
this.getGalleryDetailView().show();
this.getApplication().getController('GalleryDetailController').setPage(this.currPageNum);
},
// 폴더 리스트이 아이템이 클릭됨
onItemTapDir:function(list,index, item){
this.initGalleryList();
temp = Ext.getStore('GalleryDirStore').data.items[index].data.path;
// 해당 폴더로 이동하여 GalleryList를 보여준다.
this.getGalleryDirListView().hide();
this.getGalleryListView().setHtml('<font size=2>' + temp + '</font>');
this.getGalleryListView().show();
this.callServerTot(temp);
},
// 파일리스트를 초기화 시켜줌
initGalleryList:function()
{
this.currPageNum = 1;
Ext.getStore('GalleryStore').removeAll();
Gallery.common.GalleryData.totDataPos=0;
Gallery.common.GalleryData.maxDataPos=0;
Gallery.common.GalleryData.minDataPos=0;
Gallery.common.GalleryData.curDataPos=0;
Gallery.common.GalleryData.curId='0';
Gallery.common.GalleryData.curSubject='';
Gallery.common.GalleryData.curContent='';
Gallery.common.GalleryData.curImg='';
Gallery.common.GalleryData.orgData = new Array(0);
Gallery.common.GalleryData.totData = new Array(0);
},
// 폴더리스트로 이동함
onBackMain:function()
{
this.getGalleryListView().hide();
this.getGalleryDirListView().show();
},
// PhoneGap ---------------------------------
successRootSystem:function(directoryEntry){
dirEntry=directoryEntry;
var rootPath = dirEntry.fullPath;
window.plugins.ExecFile.searchDir('', rootPath);
},
failFileSystem:function(error){
alert('error:' + error.code);
file.releaseMask();
},
getRootDir:function( )
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem){
root= fileSystem.root;
me.successRootSystem(root);
},
function(evt){
alert('file read error!! : ' + evt.target.error.code);
console.log(">>>>" + evt.target.error.code);
//file.releaseMask();
}
);
},
onDeviceReady:function() {
document.addEventListener("menubutton", me.onMenuButton, false);
document.addEventListener("backbutton", me.onBackButton, false);
me.setPlugIn();
me.getRootDir();
},
onMenuButton:function(){
if(confirm('Exit?')== true)
{
navigator.app.exitApp();
}
},
onBackButton:function(){
if(confirm('Exit?')== true)
{
navigator.app.exitApp();
}
},
startPhoneGap:function()
{
document.addEventListener("deviceready", me.onDeviceReady, false);
},
setPlugIn:function()
{
ExecFile = function() {
};
ExecFile.getMe = function()
{
return me;
}
ExecFile.install = function(){
return window.plugins.ExecFile;
};
ExecFile.prototype._onError = function(data) {
if (typeof window.plugins.execfile.onError === "function") {
window.plugins.childBrowser.onError(data);
}
};
ExecFile.prototype.exec = function(url, options) {
cordova.exec( '', '', "ExecFile", "exec", [url, options]);
};
ExecFile.onPackageList = function(data) {
storePackageList.setData(Ext.decode(data));
Ext.getCmp('packagelist').setStore(storePackageList);
storePackageList.load();
};
ExecFile.prototype.getPackageList = function(url, options) {
cordova.exec( ExecFile.onPackageList, '', "ExecFile", "getPackageList", [url, options]);
};
ExecFile.onSearchList = function(data) {
var temp = Ext.decode(data);
for(i=0; i<temp.length;i++)
{
Gallery.common.GalleryData.totData.push(temp[i]);
}
ExecFile.getMe().callServer(1);
};
ExecFile.prototype.searchFile = function(url, options) {
cordova.exec( ExecFile.onSearchList, '', "ExecFile", "searchFile", [url, options]);
};
ExecFile.onSearchDir = function(data) {
me.getGalleryDirListView().setHtml('');
Ext.getStore('GalleryDirStore').setData(Ext.decode(data));
//storeSearchList.setData(Ext.decode(data));
Ext.getStore('GalleryDirStore').load();
ExecFile.getMe().getGalleryDirList().setStore(Ext.getStore('GalleryDirStore'));
};
ExecFile.prototype.searchDir = function(url, options) {
cordova.exec( ExecFile.onSearchDir, '', "ExecFile", "searchDir", [url, options]);
};
cordova.addConstructor(function() {
cordova.addPlugin("ExecFile", new ExecFile());
});
}
});
Controller는 주석을 달아놓았으므로 잘 해석해보세요... 이중 cordova의 기능을 사용하는데 이부분은 안드로이드 앱에서 데이터를 가져오는 부분으로 생각하세요.... 이 부분은 4탄이나 5탄쯤 설명해야 할것 같습니다.
다시 3탄으로 이어집니다. 상세화면을 설명해야죠....
센차터치2 + 폰갭 코믹뷰어 소스공개 1탄
제 책인 센차터치 + 폰갭2를 공부함으로서 최종적으로 만들수 있는 결과입니다.
만화를 보기위해 만든 어플입니다. 저작권상 만화를 캡쳐해서 올리지 못한게 조금 아쉽네요...
센차터치2 + 폰갭(안드로이드 환경) + 폰갭 플러그인 기술을 적용했습니다...
MVC모델을 준수했습니다. (책에는비 MVC를 기준으로 설명했고 새로운 유형이 나오면 MVC를 똑같은 기능을 넣어 제공했습니다... 둘을 비교하면 MVC가 어떠한 형태로 구현되는지 알수 있습니다...
1. 폴더를 먼저 올립니다. 소스를 보면 안드로이드 패키지와 폰갭 그리고 하단은 플러그인에 관련된 소스입니다...
가급적 쉽게 구현하였으므로 책을 따라하면 만드실 수 있습니다.
2. MVC 구조를 올립니다. MVC 구조를 살펴보시면 VIEW와 Controller, Model이 어떻게 구성되고 기타
Common과 같은 폴더의 구성을 보실 수 있습니다... (공부를 잘했다면 이해하실 수 있습니다.)
MVC 구조중 상단은 폴더와 파일목록을 보는 화면에 대한 Controller기준이며 하단은 만화를 보기위한 화면에 대한
컨트롤러입니다.
3. 구조를 이해하기 위해 폴더보기를 사진을 먼저 보여드립니다. 안드로이드 안에있는 각 폴더별로 이미지를 불러와
3장까지 보여주는 기능입니다....
4. 파일보기입니다. 해당 폴더의 파일이 나옵니다.. 파일을 스크롤 하여 아래로 내리면 10건씩 붙게 됩니다....
지금은 리스트가 메모리 관리에 큰 문제가 없지만... 이전에 만든거라... 30건을 유지하며 상위 10건은 삭제하도록 처리했습니
다... 따라서 리스트는 아무리 위 아래로 스크롤 해도 30건만 나옵니다....
5. 다음은 파일리스트 중 하나를 클릭하면 상세화면이 나옵니다...
이화면이 만화이어야 하는데..저작권 때문에 다른 이미지로 대체했습니다...
만화를 손가락으로 이동하여 페이지를 이동시킬 수 있습니다... 상세화면도...Carousel에서
딱 30장만 보이도록 컨트롤 했습니다... 앞뒤로 이동이 가능하고 만화를 다보고 파일목록으로 다시 이동할 경우
해당 만화를 보았던 곳으로 파일의 리스트가 자동 계산하여 이동하도록 처리했습니다...
(이부분이 센차터치 갤러리를 만드는 핵심구현부분입니다..)
6. 이 화면을 클릭하면 이미지 상세화면이 나오는데 확대 축소가 가능하도록 처리했습니다. 이화면은
생략합니다....
여기까지가 개요입닏. 2탄부터 소스를 설명합니다...계속...
만화를 보기위해 만든 어플입니다. 저작권상 만화를 캡쳐해서 올리지 못한게 조금 아쉽네요...
센차터치2 + 폰갭(안드로이드 환경) + 폰갭 플러그인 기술을 적용했습니다...
MVC모델을 준수했습니다. (책에는비 MVC를 기준으로 설명했고 새로운 유형이 나오면 MVC를 똑같은 기능을 넣어 제공했습니다... 둘을 비교하면 MVC가 어떠한 형태로 구현되는지 알수 있습니다...
1. 폴더를 먼저 올립니다. 소스를 보면 안드로이드 패키지와 폰갭 그리고 하단은 플러그인에 관련된 소스입니다...
가급적 쉽게 구현하였으므로 책을 따라하면 만드실 수 있습니다.
2. MVC 구조를 올립니다. MVC 구조를 살펴보시면 VIEW와 Controller, Model이 어떻게 구성되고 기타
Common과 같은 폴더의 구성을 보실 수 있습니다... (공부를 잘했다면 이해하실 수 있습니다.)
MVC 구조중 상단은 폴더와 파일목록을 보는 화면에 대한 Controller기준이며 하단은 만화를 보기위한 화면에 대한
컨트롤러입니다.
3. 구조를 이해하기 위해 폴더보기를 사진을 먼저 보여드립니다. 안드로이드 안에있는 각 폴더별로 이미지를 불러와
3장까지 보여주는 기능입니다....
4. 파일보기입니다. 해당 폴더의 파일이 나옵니다.. 파일을 스크롤 하여 아래로 내리면 10건씩 붙게 됩니다....
지금은 리스트가 메모리 관리에 큰 문제가 없지만... 이전에 만든거라... 30건을 유지하며 상위 10건은 삭제하도록 처리했습니
다... 따라서 리스트는 아무리 위 아래로 스크롤 해도 30건만 나옵니다....
5. 다음은 파일리스트 중 하나를 클릭하면 상세화면이 나옵니다...
이화면이 만화이어야 하는데..저작권 때문에 다른 이미지로 대체했습니다...
만화를 손가락으로 이동하여 페이지를 이동시킬 수 있습니다... 상세화면도...Carousel에서
딱 30장만 보이도록 컨트롤 했습니다... 앞뒤로 이동이 가능하고 만화를 다보고 파일목록으로 다시 이동할 경우
해당 만화를 보았던 곳으로 파일의 리스트가 자동 계산하여 이동하도록 처리했습니다...
(이부분이 센차터치 갤러리를 만드는 핵심구현부분입니다..)
6. 이 화면을 클릭하면 이미지 상세화면이 나오는데 확대 축소가 가능하도록 처리했습니다. 이화면은
생략합니다....
여기까지가 개요입닏. 2탄부터 소스를 설명합니다...계속...
피드 구독하기:
글 (Atom)




