반응형


FileCache.java

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public interface FileCache {

public FileEntry get(String key);

public void put(String key, ByteProvider provider) throws IOException;

public void put(String key, InputStream is) throws IOException;

public void put(String key, File sourceFile, boolean move) throws IOException;

public void remove(String key);

public void clear();

public boolean has(String key);
}


FileEntry.java

public class FileEntry {

private String key;
private File file;

public FileEntry(String key, File file) {
this.key = key;
this.file = file;
}

public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}

public String getKey() {
return key;
}

public File getFile() {
return file;
}

}


FileCacheImpl.java

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class FileCacheImpl implements FileCache {

private CacheStorage cacheStorage;

public FileCacheImpl(File cacheDir, int maxKBSizes) {
long maxBytesSize = maxKBSizes <= 0 ? 0 : maxKBSizes * 1024;
cacheStorage = new CacheStorage(cacheDir, maxBytesSize);
}

@Override
public FileEntry get(String key) {
File file = cacheStorage.get(keyToFilename(key));
if (file == null) {
return null;
}
if (file.exists()) {
return new FileEntry(key, file);
}
return null;
}

@Override
public void put(String key, ByteProvider provider) throws IOException {
cacheStorage.write(keyToFilename(key), provider);
}

@Override
public void put(String key, InputStream is) throws IOException {
put(key, ByteProviderUtil.create(is));
}

@Override
public void put(String key, File sourceFile, boolean move)
throws IOException {
if (move) {
cacheStorage.move(keyToFilename(key), sourceFile);
} else {
put(key, ByteProviderUtil.create(sourceFile));
}
}

@Override
public void remove(String key) {
cacheStorage.delete(keyToFilename(key));
}

private String keyToFilename(String key) {
String filename = key.replace(":", "_");
filename = filename.replace("/", "_s_");
filename = filename.replace("\\", "_bs_");
filename = filename.replace("&", "_bs_");
filename = filename.replace("*", "_start_");
filename = filename.replace("?", "_q_");
filename = filename.replace("|", "_or_");
filename = filename.replace(">", "_gt_");
filename = filename.replace("<", "_lt_");
return filename;
}

@Override
public void clear() {
cacheStorage.deleteAll();
}

@Override
public boolean has(String key) {
return cacheStorage.has(key);
}


}


IOUtils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public abstract class IOUtils {

public static String read(InputStream is) throws IOException {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
char[] readDate = new char[1024];
int len = -1;
while ((len = reader.read(readDate)) != -1) {
builder.append(readDate, 0, len);
}
return builder.toString();
} finally {
close(reader);
}
}

public static void copy(InputStream is, OutputStream out)
throws IOException {
byte[] buff = new byte[4096];
int len = -1;
while ((len = is.read(buff)) != -1) {
out.write(buff, 0, len);
}
}


public static void copy(File source, OutputStream os) throws IOException {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(source));
IOUtils.copy(is, os);
} finally {
IOUtils.close(is);
}
}

public static void copy(InputStream is, File target) throws IOException {
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(target));
IOUtils.copy(is, os);
} finally {
IOUtils.close(os);
}
}

public static void copy(String str, OutputStream os) throws IOException {
os.write(str.getBytes());
}

public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}

}


FileCacheFactory.java

import android.content.Context;
import java.io.File;
import java.util.HashMap;

public class FileCacheFactory {

private static boolean initialized = false;
private static FileCacheFactory instance = new FileCacheFactory();

public static void initialize(Context context, String file_dir) {
if (!initialized) {
synchronized (instance) {
if (!initialized) {
instance.init(context,file_dir);
initialized = true;
}
}
}
}

public static FileCacheFactory getInstance() {
if (!initialized) {
throw new IllegalStateException(
"Not initialized. You must call FileCacheFactory.initialize() before getInstance()");
}
return instance;
}

private HashMap<String, FileCache> mCacheMap = new HashMap<String, FileCache>();
private File mCacheBaseDir;

private FileCacheFactory() {
}

private void init(Context context) {
mCacheBaseDir = context.getCacheDir();
}

private void init(Context context, String file_dir) {
// cacheBaseDir = context.getCacheDir();
mCacheBaseDir = new File(file_dir);
}

public FileCache create(String cacheName, int maxKbSizes) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
File cacheDir = new File(mCacheBaseDir, cacheName);
if (cache != null) {
try {
cache = new FileCacheImpl(cacheDir, maxKbSizes);
mCacheMap.put(cacheName, cache);
} catch (Exception e) {
String.format("FileCache[%s] Aleady exists", cacheName);
}
}


return cache;
}
}

public FileCache get(String cacheName) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
if (cache == null) {
try {

}catch (Exception e)
{
String.format("FileCache[%s] not founds.", cacheName);
}
}
return cache;
}
}

public void destroy(String cacheName)
{
FileCache cache = mCacheMap.get(cacheName);

File file = new File(mCacheBaseDir+File.separator+cacheName);
if(file.exists())
{
file.delete();
}
}

public void clear(){
mCacheMap.clear();
}

public boolean has(String cacheName) {
return mCacheMap.containsKey(cacheName);
}
}

설명

캐시 디렉토리 안에 캐시파일이 여러개 저장되는 방식입니다. 


사용방법

1. 캐시 디렉토리

private FileCache mFileCache = null;

public static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "FolderName" + File.separator + ".cache"; //캐시 기본폴더

FileCacheFactory.initialize(mContext, CACHE_PATH);
if (!FileCacheFactory.getInstance().has(zipDirName)) // 해당 키의 캐시 디렉토리가 있는지 확인
{
FileCacheFactory.getInstance().create(zipDirName, 0); // 캐시디렉토리가 없을경우 만든다.
}
mFileCache = FileCacheFactory.getInstance().get(zipDirName); // 해당 파일의 캐시 디렉토리를 가져온다.


- 캐시 객체 생성

FileCacheFactory.initialize(mContext, CACHE_PATH);

- 캐시디렉토리 존재 여부 체크

FileCacheFactory.getInstance().has(Dirkey)

- 캐시디렉토리 생성

FileCacheFactory.getInstance().create(Dirkey, 0); // 캐시디렉토리가 없을경우 만든다.

- 캐시디렉토리 가져오기

mFileCache = FileCacheFactory.getInstance().get(Dirkey); // 해당 파일의 캐시 디렉토리를 가져온다.


2. 캐시 

-캐시 저장

/**
* @param key cache
* @param val cache 내용
* @param isMove ture = val파일이 캐시경로로 이동됨, false = val파일이 캐시경로로 복사됨
*/
private void setCacheFile(String key, File val, boolean isMove) {
if (!mFileCache.has(key)) {
try {
mFileCache.put(key, val, isMove);
} catch (IOException e) {
e.printStackTrace();
}
}
}

-캐시 가져오기

/**
* 캐시내용을 가져온다.
* @param key cache
* @return
*/
public FileEntry getCacheFile(String key) {

return mFileCache.get(key);
}


chche.zip


반응형
반응형

Apache Commons Compress 1.14

라이브러리를 import 해줍니다.

jar파일 다운로드 url


import org.apache.commons.compress.utils.IOUtils;

/**
* 파일 복사
*
* @return exist 복사 성공 여부

*/
public synchronized boolean copyFile(String inFilePath, String outFilePath) {
FileInputStream fis = null;
FileOutputStream fos = null;
File file = null;
boolean exist = false;
try {
fis = new FileInputStream(inFilePath);
fos = new FileOutputStream(outFilePath);
IOUtils.copy(fis, fos);

file = new File(outFilePath);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
// 마지막에 FileInputStream / FileOutputStream을 닫아준다.
if (fis != null) try {
fis.close();
}
catch (IOException e) {
Log.i("파일복사", "fileInput error");
}

if (fos != null)
try {
fos.close();
}
catch (IOException e) {
Log.i("파일복사", "fileOutput error");
}
if (file != null) {                 // 복사한 경로에 File있는지 확인
if (file.exists()) {
exist = true;
}
else {
exist = false;
}
}

}
return exist;
}



반응형
반응형

이번에 알림기능을 넣고 앱을 테스트 하면서

안드로이드 ics 버전에서 앱이 죽는 현상이 발생하여 다음과 같이 해결

public static void ViewNotice(String notiTitle ,String notiContent,Context context){ NotificationManager mNM; mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);         Intent mI = new Intent(); mI.setClass(context, NotiViewActivity.class); mI.putExtra("NOTICE", notiContent); mI.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mI, PendingIntent.FLAG_UPDATE_CURRENT);     Notification notification = null;                 //안드로이드 버전 체크 if(Build.VERSION_CODES.KITKAT<Build.VERSION.SDK_INT){                     //킷켓보다 버전 보다 높을 경우

Notification.Builder builder = new Notification.Builder(context); builder.setSmallIcon(R.drawable.icon_t); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle("공지 제목"); builder.setContentText("공지 내용"); builder.setContentIntent(contentIntent); notification = builder.build(); }else{                     //킷켓 버전이하일 경우

    notification = new Notification(R.drawable.icon_t, null, System.currentTimeMillis());     notification.setLatestEventInfo(context, "공지 제목","공지 내용", contentIntent); } notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE; notification.defaults |= Notification.DEFAULT_SOUND; mNM.notify(0, notification); }


특정버전 이하에서는 Notification notification = builder.build(); 지원하지 않는것 같음

안드로이드 ics 버전에서는 다음과 같이 정의하면 오류가 나지 않는다.

		    notification = new Notification(R.drawable.icon_t, null, System.currentTimeMillis());
	            notification.setLatestEventInfo(context, "공지 제목","공지 내용", contentIntent);




반응형
반응형

https://developer.android.com/preview/features/working-with-fonts.html?hl=ko#fonts-in-xml 

해당 페이지에서 번역하여 저 나름대로의 주관적인 의견을 더한 게시물입니다.


Android O에는 XML안에서 font리소스를 사용할 수 있는 새로운 기능이 추가되었습니다.

이제 색다른 글씨체로 안드로이드 앱을 구현할 수 있습니다.(일이 늘어날거 같은 느낌...)

Android O는 시스템 font와 관련된 정보를 검색하고 파일 설명자를 제공하는 메커니즘도 제공합니다.


Font 및 XML

Android O를 사용하면 font파일을 res / font / (요기)  해당 경로에 font를 추가하여 글꼴들을 한데 모아놓을 수 있습니다. 

이 글꼴은 R 파일에서 컴파일되며 Android Studio에서 자동으로 사용할 수 있습니다.

기존에 리소스 R.id 처럼 글꼴을 인식할 수 있습니다.

@font/myfont, or R.font.myfont.

font를 리소스로 추가하려면 Android Studio에서 다음 단계를 수행하십시오.

1. res 폴더를 마우스 오른쪽 버튼으로 클릭하고 새로 만들기> Android 리소스 디렉토리로 이동하십시오. New Resource Directory 창이 나타납니다.

2. 리소스 종류 목록에서 font을 선택한 다음 확인을 누릅니다.

참고: font파일을 넣을 디렉토리의 이름은 무조건 font여야합니다.


font 디렉토리를 만든다.


3. font 디렉토리에 font파일 추가 합니다.

아래 그림처럼 font 디렉토리에 font파일을 넣어 두면 R.font.dancing_scriptR.font.lobster 해당이름으로 font를 불러올 수 있습니다.



4. font파일을 두번 클릭하면 편집기에서 해당 파일의 font를 미리볼 수 있습니다.


XML 레이아웃에서 font를 사용

TextView 객체나 style에서 font를 쉽게 사용할 수 있습니다.

TextView 객체나 style에서 font를 연결하려면 fontFamily 특성을 사용하면 됩니다.

- TextView에 font 추가

<TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:fontFamily="@font/lobster"/>

- Style에 font 추가

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
   
<item name="android:fontFamily">@font/lobster</item>
</style>

- 코드에서 font 추가

Typeface typeface = getResources().getFont(R.font.myfont);
textView
.setTypeface(typeface);


더욱 자세한 사항은 해당페이지에서 확인 하세요.

https://developer.android.com/preview/features/working-with-fonts.html?hl=ko#retrieving-system-fonts

반응형
반응형


public abstract class BaseActivity extends AppCompatActivity {

protected ProgressDialog mProgressDialog = null;

protected abstract Context getContext();

/**
* 프로그래스를 보여준다.
*/
public void showProgressDialog() {
if (mProgressDialog == null) {
if (Build.VERSION_CODES.KITKAT < Build.VERSION.SDK_INT) {

//             R.style.ProgressDialogStyle은 커스텀으로 정의한 스타일임
mProgressDialog = new ProgressDialog(getNowContext(), R.style.ProgressDialogStyle);

} else {
mProgressDialog = new ProgressDialog(getNowContext());
}
mProgressDialog.setMessage(getString(R.string.progress_message));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
}
mProgressDialog.show();
}

/**
* 프로그래스를 숨긴다.
*/
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}

}


R.style.ProgressDialogStyle

<style name="ProgressDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:layout_centerVertical">true</item>
<item name="android:layout_centerHorizontal">true</item>
<item name="colorAccent">@color/colorPrimary</item>
</style>


사용 할 때

private class DownloadTask extends AsyncTask{


@Override
protected void onPreExecute() {
showProgressDialog(); // 작업 시작


//작업 준비 코드 작성
super.onPreExecute();
}


@Override
protected Object doInBackground(Object[] params) {
//작업 중
return null;
}

@Override
protected void onPostExecute(Object o) {
//작업 끝 코드 작성

hideProgressDialog(); // 작업 끝
super.onPostExecute(o);
}
}

 이런 느낌으로 사용하시면 됩니다.

반응형
반응형

많은 앱들이 카카오톡 처럼 탭 뷰페이저 형식을 사용합니다.



그래서 간단히 TabLayout + ViewPager + fragment 형식의 앱을 만들어서 공유드립니다.


다음과 같이 만들었는데요 


1. 라이브러리 셋팅


compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:design:25.2.0'


- AppCompatActivity클래스는 appcompatV7 라이브러리에 포함되어 있습니다.

- ViewPager클래스는 supportV4 라이브러리에 포함되어 있습니다.

- TabLayout은 design 라이브러리에 포함되어 있습니다.

2. 소스코드

MainActivity.java

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.adapter.MainTabPagerAdapter;
import pe.sk.com.myapplication.data.DummyContent;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;

public class MainActivity extends AppCompatActivity implements OnListFragmentInteractionListener {
private TabLayout mTabLayout = null; // 탭 레이아웃
private ViewPager mViewPager = null; // 뷰 페이저
private MainTabPagerAdapter mPagerAdapter = null; // 탭 어댑터

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabLayout = (TabLayout) findViewById(R.id.main_tab);
mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
mTabLayout.setupWithViewPager(mViewPager);

mPagerAdapter = new MainTabPagerAdapter(getSupportFragmentManager(), this);
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});
}

@Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
Toast.makeText(this,item.content,Toast.LENGTH_SHORT).show();
}
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.TabLayout
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="@+id/main_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#ff880033"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#bbdefa"
app:tabSelectedTextColor="#ffffff"
app:tabTextColor="#88ffffff"
/>


<android.support.v4.view.ViewPager
android:id="@+id/main_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/main_tab"
/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>

MainTabPagerAdapter.java


import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.fragment.FirstFragment;
import pe.sk.com.myapplication.fragment.TwoFragment;

/**
* Created by P092613 on 2017-03-09.
*/

public class MainTabPagerAdapter extends FragmentStatePagerAdapter {
private final static int TAB_COUNT = 2;     // 탭의 개수


private Context mContext;
private FirstFragment mFirstFragment = null;
private TwoFragment mTwoFragment = null;

private int[] mTabTitle = {R.string.first, R.string.two};

public MainTabPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.mContext = context;
}

@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
mFirstFragment = FirstFragment.newInstance(1);
return mFirstFragment;
default:
mTwoFragment = TwoFragment.newInstance(1);
return mTwoFragment;
}
}

@Override
public CharSequence getPageTitle(int position) {
return mContext.getString(mTabTitle[position]);
}

@Override
public int getCount() {
return TAB_COUNT;
}
}


FirstFragment.java 와 TwoFragment.java 코드는 동일함

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.adapter.FirstRecyclerViewAdapter;
import pe.sk.com.myapplication.data.DummyContent;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;

/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class FirstFragment extends Fragment {

// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;

/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public FirstFragment() {
}

// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static FirstFragment newInstance(int columnCount) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}

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

if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_list, container, false);

// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new FirstRecyclerViewAdapter(DummyContent.ITEMS, mListener));
}
return view;
}


@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}


}


FirstRecyclerViewAdapter.java 와 TwoRecyclerViewAdapter.java 코드는 동일함


import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.data.DummyContent.DummyItem;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;

/**
* {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
* specified {@link OnListFragmentInteractionListener}.
* TODO: Replace the implementation with code for your data type.
*/
public class FirstRecyclerViewAdapter extends RecyclerView.Adapter<FirstRecyclerViewAdapter.ViewHolder> {

private final List<DummyItem> mValues;
private final OnListFragmentInteractionListener mListener;

public FirstRecyclerViewAdapter(List<DummyItem> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_first, parent, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);

holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}

@Override
public int getItemCount() {
return mValues.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyItem mItem;

public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}

@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}


fragment_first_list.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/list"
android:name="pe.sk.com.myapplication.fragment.FirstItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context="pe.sk.com.myapplication.fragment.FirstFragment"
tools:listitem="@layout/fragment_first"/>


fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>

<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>
</LinearLayout>


반응형
반응형

간혹 안드로이드 스튜디오를 실행해보면 다음과 같은 오류를 만날 수 있습니다.

Error:Unable to start the daemon process.

This problem might be caused by incorrect configuration of the daemon.

For example, an unrecognized jvm option is used.

Please refer to the user guide chapter on the daemon at https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html

Please read the following process output to find out more:

-----------------------

Error occurred during initialization of VM

Could not reserve enough space for 1572864KB object heap



이럴 경우 당황하지 말고 

gradle.properties 파일로 들어가서 Xmx1536m -> Xmx512m 으로 변경해준다.

저장 후 상단 오른쪽에 Try again을 눌러주면 끝

반응형
반응형

개발을 하다보면 이러한 오류를 만날 수 있습니다.

이럴때는 당황하지 말고

Poject의 build.gradle에 compile 'com.android.support:design:25.2.0' lib를 추가하시면 해결 됩니다.





반응형

+ Recent posts