안드로이드 java Arraylist 역순 정렬 소스 입니다.

Comparator comparator = Collections.reverseOrder();

Collections.sort(리스트(Arraylit), myComparator);

Collections.reverse(리스트(Arraylit));

private final static Comparator

myComparator= new Comparator() {
private final Collator collator = Collator.getInstance();
@Override
public int compare(AJContent object1 , AJContent object2) {
return collator.compare(object1.getNo(), object2.getNo());
 } };



안드로이드 Notification 이용 방법에도 여러 가지가 있습니다.

상태바 알림을 사용할 때에는 개잘 중인 앱이 SDK 11 이상인지 이하인지 

잘 체크 해서 사용해야 합니다.

오늘 시간이 없어서 코드만 간략하게 올려 봅니다 

도움 되시길 바라며 ^^


아래소스는 옛(구) 버전의 notification 소스 코드입니다.

모든 OS 호환 되며 가장 기본 적인 Title , text , icon , ticker 이용시 사용되는 코드 입니다.

  ii.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK  | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);
  PendingIntent pendingIntent = PendingIntent.getActivity(context, Code, ii, PendingIntent.FLAG_UPDATE_CURRENT);
  Notification notification = new Notification();
  notification.icon = R.drawable.ic_launcher;
  notification.tickerText = ticker 에 보여질 메시지;
  notification.when = System.currentTimeMillis();
  notification.vibrate = new long[] { 500, 100, 500, 100 };
  notification.sound = Uri.parse("/system/media/audio/notifications/20_Cloud.ogg");
  notification.defaults |= Notification.DEFAULT_SOUND;
  notification.flags = Notification.FLAG_AUTO_CANCEL;
  notification.setLatestEventInfo(context, getString(R.string.app_name) , msg , pendingIntent);
  notificationManager.notify(Code, notification);

아래 소스는 최신 업데이트된 notification  소스 입니다. 

하지만 아래 소스를 사용하신다면 확인 하셔야 할 부분이 있습니다.

제가 테스트한 폰은 갤럭시s4 LTE 입니다. 다른 폰에서는 아직 테스트 해보진 않았지만

아래 소스를 사용할경우 contenttext 를 입력하여 notification을 사용하시게 되면 이상하게 

가끔 상태바 알림 제목은 나오나 내용이 안나오는 경우가 있는데 

좀더 테스트를 해보시구 확인 해보셔야 할 듯합니다. 


위에서 말한 오류만 아니라면 새롭게 업데이트 된 notification 은 다양하게 이용 가능하고 좋습니다.

상태알림 바에서 아래로 드레그하게 되면 상세내용도 확인 할 수 있도로 가능하며 

tag 값도 입력하여 여러가지로 다양하게 꾸밀 수 있습니다. view(뷰)까지 추가 가능하기때문에

이미지나 뷰를 추가하여 다양하게 효율 적으로 사용 가능하여 좋은 것 같습니다.


// Notification.Builder builder =  new Notification.Builder(ctx)  sdk 11 이상 사용가능
NotificationCompat.Builder builder =  new NotificationCompat.Builder(ctx)  //sdk 11이전 버전도 호환 가능 하기 위하여 나옴
Intent ii = new Intent(getApplicationContext(), 클레스네임.class);
ii.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK  | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, ii, PendingIntent.FLAG_UPDATE_CURRENT);  
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(getString(R.string.app_name));
builder.setTicker( ticker 에 보여질 메시지 );
builder.setContentText( 상태바를 내리면 보여질 메시지);
builder.setContentIntent(contentIntent);  
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.BigTextStyle());
NotificationManager manager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);  
 manager.notify(Code, builder.build());  
안드로이드 페이스북 간편하게 Intent 로 공유하는 방법입니다.

페이스북 API 를 사용 할 수도있지만 
인터넷 주소를 공유 한다고하면 API 까지 사용하지 않아도 
Intent 로 사용하는 것도 좋은것 같습니다.

if ( isPackageInstalled("com.facebook.katana") ){

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);

shareIntent.setType("text/plain");

shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "나눔Tv"); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://www.ajunews.com/view/20140609101252520");

shareIntent.setClassName("com.facebook.katana", "com.facebook.katana.activity.composer.ImplicitShareIntentHandler");

startActivity(shareIntent);

} else {

Toast.makeText(getActivity(), "페이스북 앱 설치 후 이용해주세요.", Toast.LENGTH_SHORT).show(); // }


안드로이드 이번 킷캣 (kitkat ) 업데이트 되면서 ios 처럼 상태바가 변경 되었는데요

키캣으로 업데이트 되면서 안드로이드 상태바도  ios 상단바 처럼 투명처리와 함께 

앱과 하나 되어지기게 수정 할 수 있게 되었습니다.


현재 적용되어 있는앱은 카카오 스토리인것 같은데요

킷캣으로 업데이트 이후 카카오스토리를 실행 해보시면 아~ 하길서에요 ^^

아래 이미지는 킷캣전 상단바 앱을 실행하면 보여지는 검정 바탕입니다.



그럼 아래 소스를 안드로이드 프로젝트를 만들고  

메니페스트에 Notitle 설정 후 메인에 아래 소스를 입력 해주세요 

그런 후 실행 해 보시면 ㅎㅎ 

앱이 상태바와 하나가 되어 이뻐진 모습을 볼 수가 있습니다. ^^


int id = getResources().getIdentifier("config_enableTranslucentDecor", "bool", "android");

  if (id != 0 && getResources().getBoolean(id)) { // Translucent available

    Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); w.setBackgroundDrawableResource(R.drawable.a_00_navi);

}


아래는 적용 후 폰 상태입니다.  

그럼 모두들 즐거운 개발 하세요 ^^ 


안드로이드 레이아웃 사이즈를 구하고 동적으로 가로 세로 사이즈를 변경 할때 

고생 하시는분들을 위한 레이아웃 (layout) 사이즈 구하는 방벙을 모아 봤습니다.


아래 소스는 layout 의 가로 세로 사이즈를 구하고 layout 의 가로 세로 사이즈를 수정 하는 방법 입니다.

추가로 layout 사이즈를 구하는 소를 응용하여 가로 세로 사이즈를 비율로 동적으로 수정하는 방법으로 

올렸습니다.


아래 소스에 좋은 의견이나 문제가 있는 부분은 댓글로 달아 주시면 감사하겠습니다.


레이아웃 onWindowFocusChanged(boolean hasFocus) 를 이용한 사이즈 구하기 방법입니다.

@Override

public void onWindowFocusChanged(boolean hasFocus) {

View layoutMainView = (View)this.findViewById(R.id.mainLayout);

Log.w("Layout Width - ", String.valueOf(layoutMaintView.getWidht()));

Log.w("Layout Height - ", String.valueOf(layoutMaintView.getHeight()));

}


레이아웃 post trhead를 이용한 레이아웃 사이즈를 구하는 방법 

( 참고: 레이아웃이 생성된 후 사이즈를 구하기 때문에 사이즈를 구한 후 사이즈를 이용하여 다른 작업 하기에는 시간차가 있습니다. )

final LinearLayout layout = (LinearLayout)view.findViewById(R.id.capaign_row_img_lay); layout .post(new Runnable() {

@Override public void run() {

Log.e(" size ", "Width size= " + layout .getWidth());

Log.e(" size ", "Height size= " + layout .getHeight()); } });


레이아웃 OnGlobalLaoutListener 이용한 방법 ( 사이즈를 구하고 동적으로 사이즈 수정하는데 가장 효과적인듯 합니다. )

final LinearLayout layout = (LinearLayout)view.findViewById(R.id.capaign_row_img_lay); ViewTreeObserver vto = imglay.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

@Override

public void onGlobalLayout() {

layout .getViewTreeObserver().removeGlobalOnLayoutListener(this);

int width = layout .getMeasuredWidth();

int Height = imglay.getMeasuredHeight(); } });


위에방법을 응용한 사이즈 구한 후 비율로 세로 사이즈를 변경 하는 소스 입니다. 

( 이미지를 일정 비율로 작업하고 비율로 여러 해상도에 보여주기 위한 방법  참고: 제가 만든 예제 임으로 머라구 하지마세요 ^^)


final LinearLayout layout = (LinearLayout)view.findViewById(R.id.capaign_row_img_lay);

 final LayoutParams mLayoutParam = (LayoutParams)layout.getLayoutParams();     mLayoutParam.height   = ScreenSize(위에 설명 드린 소스를 사용하여 사이즈를 구하여 가로 사이즈를 입력); layout.setLayoutParams(mLayoutParam); layout.setGravity(Gravity.CENTER);

/**

* @return 4:2 사이즈 비율 세로사이즈 리턴

*/

public int ScreenSize(int width){

  int size = 0;

//아래주석을 풀면 해상도 사이즈를 구해서 세로 사이즈를 구합니다.

//DisplayMetrics mDisplay = new DisplayMetrics(); //mContext.getWindowManager().getDefaultDisplay().getMetrics(mDisplay);

// size = mDisplay.widthPixels

  size = width;

  size = size / 4;

  size = size * 2;

  return size;

}

뷰페이저 ( viewpager ) 를 WRAP_CONTENT 로 설정을 해도 match_parent 적용 되는 문제 해결


viewpager 아래에 layout을 둬야 하는데 무조건 match_parent 적용되는 viewpager 때문에 

고생하시는 분들이라면 참고하세요 ^^



Custom viewpagr 만들어 사용하는 방법

 
public class HeightWrappingViewPager extends ViewPager {
   public HeightWrappingViewPager(Context context) {
        super(context);
    }

    public HeightWrappingViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) 
                == MeasureSpec.AT_MOST;

        if(wrapHeight) {
            /**
             * The first super.onMeasure call made the pager take up all the 
             * available height. Since we really wanted to wrap it, we need 
             * to remeasure it. Luckily, after that call the first child is 
             * now available. So, we take the height from it. 
             */

            int width = getMeasuredWidth(), height = getMeasuredHeight();

            // Use the previously measured width but simplify the calculations
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);

            /* If the pager actually has any children, take the first child's 
             * height and call that our own */ 
            if(getChildCount() > 0) {
                View firstChild = getChildAt(0);

                /* The child was previously measured with exactly the full height.
                 * Allow it to wrap this time around. */
                firstChild.measure(widthMeasureSpec, 
                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));

                height = firstChild.getMeasuredHeight();
            }

            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

viewpagr onPageChangeListener 사용하는 방법

@Override
public Object instantiateItem(ViewGroup collection, int page) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = (View) inflater.inflate(R.layout.page_item , null);
    view.setTag(page);
private ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    pager = findViewById(R.id.viewpager);
    pager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            resizePager(position);
        }
    });

    public void resizePager(int position) {
        View view = pager.findViewWithTag(position);
        if (view == null) 
            return;
        view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
            //The layout params must match the parent of the ViewPager 
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width height); 
        pager.setLayoutParams(params);
    }
}

+ Recent posts