package be.digitalia.common.widgets;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.util.ObjectsCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowInsets;
import android.widget.FrameLayout;
/**
* A FrameLayout which memorizes the window insets and propagates them to child views before they are measured.
* You can use this layout as a fragment container in place of a standard FrameLayout to
* propagate window insets to attached fragments.
*
* @author Christophe Beyls
*/
public class WindowInsetsFrameLayout extends FrameLayout {
private Object mLastInsets;
public WindowInsetsFrameLayout(Context context) {
super(context);
}
public WindowInsetsFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (!ObjectsCompat.equals(mLastInsets, insets)) {
mLastInsets = insets;
requestLayout();
}
return insets.consumeSystemWindowInsets();
}
@SuppressWarnings("deprecation")
@Override
protected boolean fitSystemWindows(Rect insets) {
if (!ObjectsCompat.equals(mLastInsets, insets)) {
if (mLastInsets == null) {
mLastInsets = new Rect(insets);
} else {
((Rect) mLastInsets).set(insets);
}
requestLayout();
}
return true;
}
@SuppressLint("DrawAllocation")
@SuppressWarnings("deprecation")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mLastInsets != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
final WindowInsets wi = (WindowInsets) mLastInsets;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.dispatchApplyWindowInsets(wi);
}
}
} else {
super.fitSystemWindows(new Rect((Rect) mLastInsets));
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
/*
* Copyright (C) 2012 Sebastian Kaspari
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androidzeitgeist.adapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
/**
* Implementation of {@link PagerAdapter} that represents each page as a {@link View}.
*
* @author Sebastian Kaspari <sebastian@androidzeitgeist.com>
*/
public abstract class ViewPagerAdapter extends PagerAdapter
{
/**
* Get a View that displays the data at the specified position in the data set.
*
* @param position The position of the item within the adapter's data set of the item whose view we want.
* @param pager The ViewPager that this view will eventually be attached to.
*
* @return A View corresponding to the data at the specified position.
*/
public abstract View getView(int position, ViewPager pager);
/**
* Determines whether a page View is associated with a specific key object as
* returned by instantiateItem(ViewGroup, int).
*
* @param view Page View to check for association with object
* @param object Object to check for association with view
*
* @return true if view is associated with the key object object.
*/
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
/**
* Create the page for the given position.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
*
* @return Returns an Object representing the new page. This does not need
* to be a View, but can be some other container of the page.
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewPager pager = (ViewPager) container;
View view = getView(position, pager);
pager.addView(view);
return view;
}
/**
* Remove a page for the given position.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param view The same object that was returned by instantiateItem(View, int).
*/
@Override
public void destroyItem(ViewGroup container, int position, Object view) {
((ViewPager) container).removeView((View) view);
}
}
public class FirebasePushIdGenerator {
// Modeled after base64 web-safe chars, but ordered by ASCII.
private final static String PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
// Timestamp of last push, used to prevent local collisions if you push twice in one ms.
private static long LAST_PUSH_TIME = 0L;
// We generate 72-bits of randomness which get turned into 12 characters and
// appended to the timestamp to prevent collisions with other clients. We store the last
// characters we generated because in the event of a collision, we'll use those same
// characters except "incremented" by one.
private static int[] LAST_RAND_CHARS = new int[72];
public static synchronized String generate() {
long now = System.currentTimeMillis();
boolean duplicateTime = now == LAST_PUSH_TIME;
LAST_PUSH_TIME = now;
char[] timeStampChars = new char[8];
for (int i = 7; i >= 0; i--) {
timeStampChars[i] = PUSH_CHARS.charAt((int)(now % 64));
now = (long) Math.floor(now / 64);
}
if (now != 0) {
throw new AssertionError("We should have converted the entire timestamp.");
}
StringBuilder id = new StringBuilder(20);
for (char c : timeStampChars) {
id.append(c);
}
if (!duplicateTime) {
for (int i = 0; i < 12; i++) {
LAST_RAND_CHARS[i] = (int) Math.floor(Double.valueOf(Math.random() * 64).intValue());
}
} else {
// If the timestamp hasn't changed since last push, use the same random number,
//except incremented by 1.
int i=0;
for (i = 11; i >= 0 && LAST_RAND_CHARS[i] == 63; i--) {
LAST_RAND_CHARS[i] = 0;
}
LAST_RAND_CHARS[i]++;
}
for (int i = 0; i < 12; i++) {
id.append(PUSH_CHARS.charAt(LAST_RAND_CHARS[i]));
}
if (id.length() != 20) {
throw new AssertionError("Length should be 20.");
}
return id.toString();
}
}
## Аннотация для идентификатора
***@Id*** - определяет поле сущности, которое будет использовано в качестве такого идентификатор.
Одно из требований фреймворка — каждая таблица должна иметь такой идентификатор.
## Аннотации для генерирования последовательности
1 ***@SequenceGenerator*** - опредeление генератора последовательности
Атрибуты:
* ***name*** - имя генератора последовательности
* ***allocationSize*** - не означает, что идентификаторы сущностей увеличатся на это значение, но это число, после которого запрос к базе данных будет выполнен снова, чтобы получить следующее значение последовательности базы данных.
* ***sequenceName*** - определяется генератор последовательности,в нашем случае он был используется общий созданный заранее
2 ***@GeneratedValue*** - определяет стратегию генерации уникального идентификатора с использованием SEQUENCE
Атрибуты:
* ***strategy*** - стратегия генерации уник ИД
* ***generator*** - используемый генератор
## Аннотация для поля
1 ***@Column*** - определяет что данное поле имеет связанное отображение в БД
2 ***@Temporal*** - применяется для преобразования из типа БД SQL в J ava и обратно. Например применяется к полям или свойствам с типом java.util.Date для преобразования из java.sql.Timestamp
// Step 1 : Create a color in color.xml file
<color name="user_color"> #008577 </color>
// user_text is the string name in strings.xml file
user_text.setTextColor(getResources().getColor(R.color.user_color));
// In Button onClick
Toast.makeText(getApplicationContext(),"Button was pressed",Toast.LENGTH_SHORT).show();
// Using Strings.xml reference
Toast.makeText(getApplicationContext(), R.string.abc ,Toast.LENGTH_SHORT).show();