I tried to create a profile preference like WhatsApp where the profile photo is shared with the profile activity. I used the following code which works properly in Android 8 and above. But in Android 7 and below, the shared element animation does not work. This is the result of a test on API 21.
Irrelevant codes have been removed.
SettingsActivity.java :
public class SettingsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setupToolbar();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.pref_content, new MainPreferenceFragment())
.commit();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (NullPointerException e) {
e.printStackTrace();
}
}}
MainPreferenceFragment.java :
import android.transition.TransitionInflater;
import androidx.core.app.ActivityOptionsCompat;
import androidx.preference.ListPreference;
import androidx.transition.Explode;
import androidx.transition.Fade;
import androidx.transition.Transition;
public class MainPreferenceFragment extends PreferenceFragmentCompat {
public static final String KEY_PROFILE = "pref_profile_key";
private File myPhotoFile;
private int profileIconSize;
private Preference profile;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
Context context = getContext();
initPreferences(context);
setListeners(context);
}
#Override
public void onResume() {
super.onResume();
profile.setTitle(MainBroadcastReceiver.getMyDeviceName());
if (myPhotoFile.exists()) {
profile.setIcon(
new BitmapDrawable(getResources(), ThumbnailUtils.extractThumbnail(
BitmapFactory.decodeFile(myPhotoFile.getPath()), profileIconSize, profileIconSize)));
} else {
profile.setIcon(R.drawable.avatar_contact);
}
}
private void initPreferences(Context context) {
profile = findPreference(KEY_PROFILE);
profile.setSummary(MainBroadcastReceiver.getMyDeviceMacAddress());
myPhotoFile = FileManager.myPhotoFile(context);
profileIconSize = ActivityManager.dp2px(context, 67F);
}
private void setListeners(Context context) {
profile.setOnPreferenceClickListener(preference -> {
AppCompatActivity activity = (AppCompatActivity) getActivity();
Intent intent = new Intent(activity, ProfileActivity.class);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setExitTransition(TransitionInflater.from(activity).inflateTransition(R.transition.fade));
View profileView = getListView().getChildAt(profile.getOrder());
ImageView profileImageView = profileView.findViewById(android.R.id.icon);
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity
, profileImageView, profileImageView.getTransitionName());
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
return true;
});
}}
preference_profile.xml :
<androidx.constraintlayout.widget.ConstraintLayout 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/chat_row_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">
<LinearLayout
android:layout_width="0dp"
android:layout_height="1dp"
android:background="?attr/dividerColor"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:singleLine="true"
android:text="Okay, Bye."
android:textAlignment="gravity"
android:textColor="?android:attr/textColorSecondary"
android:textSize="14sp"
android:transitionName="macTransition"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#android:id/title"
app:layout_constraintTop_toBottomOf="#android:id/title" />
<TextView
android:id="#android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:singleLine="true"
android:text="Robert Downey"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textSize="22sp"
android:transitionName="nameTransition"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toTopOf="#android:id/summary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toEndOf="#android:id/icon"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#android:id/icon"
android:layout_width="67dp"
android:layout_height="67dp"
android:layout_marginStart="14dp"
android:layout_marginLeft="14dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="17dp"
android:src="#drawable/avatar_contact"
android:transitionName="imageTransition"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
preferences.xml:
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.preference.Preference
android:icon="#drawable/avatar_contact"
android:key="pref_profile_key"
android:layout="#layout/preference_profile"
android:summary="u:n:k:n:o:w:n"
android:title="#string/unknown" />
</androidx.preference.PreferenceScreen>
ProfileActivity.java :
import android.transition.Transition;
import android.transition.TransitionInflater;
public class ProfileActivity extends BaseActivity {
private SimpleDraweeView imageDrawee;
private ImageView setImageImageView;
private boolean isBackPressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupTransition();
}
private void setupTransition() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setAllowEnterTransitionOverlap(true);
Transition fade = TransitionInflater.from(this).inflateTransition(R.transition.fade);
fade.excludeTarget(R.id.setImage, true);
getWindow().setEnterTransition(fade);
getWindow().getSharedElementEnterTransition().addListener(new Transition.TransitionListener() {
#Override
public void onTransitionStart(Transition transition) {
}
#Override
public void onTransitionEnd(Transition transition) {
if (!isBackPressed) {
setImageImageView.setVisibility(View.VISIBLE);
ScaleAnimation scaleUp = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
setImageImageView.startAnimation(scaleUp);
}
}
#Override
public void onTransitionCancel(Transition transition) {
}
#Override
public void onTransitionPause(Transition transition) {
}
#Override
public void onTransitionResume(Transition transition) {
}
});
} else {
setImageImageView.setVisibility(View.VISIBLE);
ScaleAnimation scaleUp = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
setImageImageView.startAnimation(scaleUp);
}
}
#Override
public void onBackPressed() {
isBackPressed = true;
ScaleAnimation scaleUp = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
scaleUp.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
setImageImageView.setVisibility(View.INVISIBLE);
ProfileActivity.super.onBackPressed();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
setImageImageView.startAnimation(scaleUp);
}}
activity_profile.xml :
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/image"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_marginTop="24dp"
android:transitionName="imageTransition"
app:actualImageScaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appbar"
app:placeholderImage="#drawable/ic_settings_profile"
app:placeholderImageScaleType="centerCrop"
app:roundAsCircle="true" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/setImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="2dp"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_home_camera"
android:tint="#color/white"
android:visibility="invisible"
app:backgroundTint="#color/colorPrimaryLight"
app:fabCustomSize="48dp"
app:layout_constraintBottom_toBottomOf="#+id/image"
app:layout_constraintEnd_toEndOf="#+id/image"
app:rippleColor="#color/white" />
</androidx.constraintlayout.widget.ConstraintLayout>
syles.xml :
<resources>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar" />
<style name="AppTheme" parent="AppTheme.Base">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
styles.xml (v21) :
<resources>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActivityTransitions">true</item>
<item name="android:windowEnterTransition">#transition/explode</item>
<item name="android:windowExitTransition">#transition/explode</item>
<item name="android:windowSharedElementEnterTransition">
#transition/change_image_transform
</item>
<item name="android:windowSharedElementExitTransition">
#transition/change_image_transform
</item>
</style>
</resources>
change_image_transition.xml :
<transitionSet>
<changeImageTransform />
<changeBounds />
</transitionSet>
explode.xml (v21) :
<explode xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground" />
<target android:excludeId="#android:id/navigationBarBackground" />
<target android:excludeId="#id/appbar" />
</targets>
</explode>
fade.xml (v21) :
<fade xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground" />
<target android:excludeId="#android:id/navigationBarBackground" />
<target android:excludeId="#id/appbar" />
</targets>
</fade>
APIs below 26 simple have different stuff so you might want to consider replacing your animation with another in api 26 and below ( and other stuff but maybe not in this application in general you can google and go to andoid official website to check that.
So simply your might not most of the devices which have api 26 and below.
Consider testing on physical devices as well to be sure.
go here and make sure to chose 26 in api drop menu top left.
https://developer.android.com/reference/android/view/animation/package-summary
good luck
I found the cause of this problem and the solution. The problem was not with the code I wrote in the question, but with the use of dynamic language in my BaseActivity. The dynamic language I implemented, in Android 7 and below recreated activity each time on the onResume method. And every time an activity was recreated, the transition animation did not work. To solve this problem, I disabled the dynamic language for my ProfileActivity.
Related
My MainActivity lags/not scrolling smoothly while using android older versions (oreo for example) but works smoothly in the latest version , I'm facing this trouble only in the main page only , the main layout is Coordinator layout.
this is the main :
public class MainActivity extends AppCompatActivity {
// Menu options :
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
dataBase db =new dataBase(this);
Toolbar toolbar;
CoordinatorLayout coordinatorLayout;
boolean ischecked =false;
LottieAnimationView lotti ;
AppCompatImageView logo ;
Animation animation ;
// the main options :
AppCompatImageView imageView1 ;
AppCompatImageView imageView2 ;
AppCompatImageView imageView3 ;
AppCompatImageView imageView4 ;
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Tablet Screen Configuration :
int seze = getResources().getConfiguration().screenLayout;
if ((seze & Configuration.SCREENLAYOUT_SIZE_XLARGE)== Configuration.SCREENLAYOUT_SIZE_XLARGE ) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
}
//end of configuration
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
imageView3 = findViewById(R.id.imageView3);
imageView4 = findViewById(R.id.imageView4);
// DataBase Stuff :
SharedPreferences shrd2 = getSharedPreferences("forbidden",MODE_PRIVATE);
int e=shrd2.getInt("d",0);
if (e==0) {
db.createDataBase();
SharedPreferences shrd= getSharedPreferences("forbidden",MODE_PRIVATE);
SharedPreferences.Editor editor=shrd.edit();
editor.putInt("d",1);
editor.apply();
}
// end of DataBase Stuff
// Images and main layout Yoyo animation Effect :
YoYo.with(Techniques.Bounce).duration(1100).delay(500).playOn(imageView1) ;
YoYo.with(Techniques.Bounce).duration(1100).delay(1100).playOn(imageView2) ;
YoYo.with(Techniques.Bounce).duration(1100).delay(2100).playOn(imageView3) ;
YoYo.with(Techniques.Bounce).duration(1100).delay(3100).playOn(imageView4)
// Logo amimation :
logo = findViewById(R.id.logo) ;
animation = AnimationUtils.loadAnimation(this,R.anim.floating);
logo.startAnimation(animation) ;
// CoordiantorLayout animated background :
coordinatorLayout = findViewById(R.id.CoordinatorLayout);
AnimationDrawable animationDrawable = (AnimationDrawable) coordinatorLayout.getBackground();
animationDrawable.setEnterFadeDuration(2500);
animationDrawable.setExitFadeDuration(5000);
animationDrawable.start();
// Toolbar Menu :
toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.MaToolBar);
toolbar.inflateMenu(R.menu.mainmenu);
// Floating button explosion transition :
final boolean[]r=new boolean[1] ;
r[0]=false;
final FloatingActionButton button = findViewById(R.id.fab);
final int[] x =new int[1];
final int[] y=new int[1];
button.post(() -> {
// Values should no longer be 0
int[] point = new int[2];
button.getLocationInWindow(point); // or getLocationInWindow(point)
x[0] = point[0];
y[0] = point[1];
r[0]=true;
final int[] xx=new int[1];
final int[] yy=new int[1];
xx[0] = x[0];
yy[0] = y[0];
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (r[0]==true) {
// startActivity(new Intent(MainActivity.this, BookMark_Activity.class));
Intent getPosition = new Intent(MainActivity.this, BookMark_Activity.class);
getPosition.putExtra("x", xx[0]);
getPosition.putExtra("y", yy[0]);
getPosition.putExtra("ShouldRun",true);
startActivity(getPosition);
}
}
});
});
// end of Floating button explosion transition
// Lottie Animation bottom :
LottieAnimationView lottieAnimationView= findViewById(R.id.lottiebottom);
lottieAnimationView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ischecked){
lottieAnimationView.setSpeed(-1);
lottieAnimationView.playAnimation();
ischecked=false;
}else {
lottieAnimationView.setSpeed(1);
lottieAnimationView.playAnimation();
ischecked=true;
}
}
});
} // end of OnCreate method
//floating button animation stuff
private int getDips(int dps) {
Resources resources = getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dps,
resources.getDisplayMetrics());
}
//Images Options for intent :
public void options (View view){
if(view.getTag().toString().equals("Is101")) {
Intent intent = new Intent(this,welcome.class) ;
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in_right , R.anim.slide_out_left);
}else if (view.getTag().toString().equals("Ar")) {
Intent intent = new Intent(this,welcome_ar.class) ;
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in_right , R.anim.slide_out_left);
}else if (view.getTag().toString().equals("HRLC")) {
Intent intent = new Intent(this,welcome_hrlc.class) ;
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in_right , R.anim.slide_out_left);
}else if (view.getTag().toString().equals("HIST")) {
Intent intent = new Intent(this,welcome_hist.class) ;
startActivity(intent);
finish();
overridePendingTransition(R.anim.slide_in_right , R.anim.slide_out_left);
}
}
public void onBackPressed() {
// Dialog box :
ViewDialogMain alert2 = new ViewDialogMain();
alert2.showDialog(MainActivity.this, "Bahrain Exams");
}
} // end of the class
and this is the XML :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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/CoordinatorLayout"
layout_height="7dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_list">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:src="#drawable/bookmarkpngg"
app:backgroundTint="#AFAEAE"
app:layout_anchor="#id/appbarLayout"
app:layout_anchorGravity="bottom|right|end" />
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbarLayout"
android:layout_width="match_parent"
android:layout_height="234dp"
android:background="#drawable/transpa_colorerd"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:contentScrim="#color/app_color"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
app:title="Bahrain Exams"
app:titleEnabled="true"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottiesecond"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="40dp"
android:layout_marginEnd="35dp"
android:layout_marginBottom="13dp"
android:rotation="-7.1"
android:scaleType="fitEnd"
android:scaleX="1.3"
android:scaleY="1.3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.796"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_rawRes="#raw/flyingman" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/logo"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginEnd="249dp"
android:layout_marginBottom="40dp"
android:src="#drawable/officiallogosecond"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.appcompat.widget.Toolbar
android:id="#+id/MaToolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:layout_collapseMode="pin" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="#+id/scroll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/transpa_scroll"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="none"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/alconstreain2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:fitsSystemWindows="true"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:background="#drawable/is"
android:foreground="#drawable/is"
android:onClick="options"
android:scaleType="fitXY"
android:src="#drawable/uob"
android:tag="Is101" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginBottom="5dp"
android:foreground="#drawable/Ar"
android:onClick="options"
android:scaleType="fitXY"
android:src="#drawable/eglish"
android:tag="Ar" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginBottom="5dp"
android:foreground="#drawable/hrlc"
android:onClick="options"
android:scaleType="fitXY"
android:src="#drawable/maths"
android:tag="HRLC" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginBottom="5dp"
android:foreground="#drawable/hist"
android:onClick="options"
android:scaleType="fitXY"
android:src="#drawable/hist"
android:tag="HIST" />
</androidx.appcompat.widget.LinearLayoutCompat>
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottiebottom"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="20dp"
android:padding="0dp"
android:scaleType="fitStart"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout3"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_rawRes="#raw/taskman" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is most likely Compatibility issues.
Make sure all your Project structure take advantage of the Android Jetpack Architecture.
For Example:
use AppCompatButton instead of Button
use LinearLayoutCompat instead of LinearLayout
... and so on.
I am creating a Relative layout which I want should come from above sliding into the layout so here's what I did
made the layout invisible
In oncreate animated the layout above the screen
and in onWindowsFocusChanged() I called animation , made layout visible and want layout to slide into the screen
BUT
when view is created the layout is at its right location with out showing any sliding effect from coming from top of screen
public class OverlayActivity extends Activity implements View.OnClickListener {
RelativeLayout question_box;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overlay);
// Slide Up the INVISIBLE layout so that I can call it by animation back to its original position
question_box = findViewById(R.id.question_box);
question_box.animate().translationY(-question_box.getHeight());
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
public void animateInObjects() {
question_box.setVisibility(View.VISIBLE);
question_box.animate().setDuration(1000).translationY(0);
}
#Override
public void onClick(View v) {
//Some Code
}
#Override
protected void onStop() {
super.onStop();
finish();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
animateInObjects();
super.onWindowFocusChanged(hasFocus);
}
}
Layout
<RelativeLayout
android:id="#+id/question_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:layout_marginTop="5dp"
android:layout_below="#+id/ad_view_container"
android:visibility="invisible">
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/questiontext"
android:paddingStart="20dp"
android:paddingTop="7dp"
android:paddingEnd="20dp"
android:paddingBottom="20dp"
android:text="#string/sample_question"
android:textAlignment="center"
android:textColor="#color/text_quest"
android:textSize="23sp" />
<View
android:id="#+id/center_vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_centerVertical="true" />
<LinearLayout
android:id="#+id/cover_opt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/question"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/main_layout">
<Button
android:id="#+id/opt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="1dp"
android:layout_marginHorizontal="2dp"
android:background="#android:color/transparent"
android:text="#string/sample_number"
android:textAlignment="center"
android:textColor="#color/text_quest"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/cover_opt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/question"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/main_layout">
<Button
android:id="#+id/opt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="1dp"
android:layout_marginHorizontal="2dp"
android:background="#android:color/transparent"
android:text="#string/sample_number"
android:textAlignment="center"
android:textColor="#color/text_quest"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/cover_opt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/question"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp"
android:layout_marginEnd="15dp"
android:background="#drawable/main_layout">
<Button
android:id="#+id/opt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="1dp"
android:layout_marginHorizontal="2dp"
android:background="#android:color/transparent"
android:text="#string/sample_number"
android:textAlignment="center"
android:textColor="#color/text_quest"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
this is the theme of the activity
<style name="Theme.Lockscreen" parent="Theme.AppCompat.NoActionBar">
<item name="android:background">#33000000</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">#null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">#android:style/Animation</item>
</style>
well you try to animate the view in onCreate method. at first the view is not drawn yet and you get a getHeight = 0 .so you must wait when the view is drawn by using view.getViewTreeObserver().addOnGlobalLayoutListener to be able to animate it
you need to add this on your onCreate() :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
// Slide Up the INVISIBLE layout so that I can call it by animation back to its original position
question_box = findViewById(R.id.question_box);
question_box.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (question_box.getHeight() != 0)
question_box.animate().translationY(-question_box.getHeight());
}
});
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
Try this as your xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromYScale="0"
android:toYScale="50%"
android:duration="1000"></scale>
</set>
To have it till half of your screen and arrange layout respectively
I have activity_main.xml with two Layouts:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#color/appColor">
<android.support.constraint.ConstraintLayout
android:id="#+id/loading_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor">
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="#+id/imageView"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/imageView"
android:indeterminateTint="#color/white"
android:indeterminateTintMode="src_in"/>
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout
android:id="#+id/webview_layout"
android:visibility="gone"
android:background="#color/appColor"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor"/>
</android.support.constraint.ConstraintLayout>
First I show the loading_layout and when I finish loading the app shows the webview_layout:
ConstraintLayout loadingLayout;
ConstraintLayout webviewLayout;
WebView webview;
String kAppUrl = "*******";
String kDefaultAppUrl = "******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
loadingLayout = (ConstraintLayout)findViewById(R.id.loading_layout);
webviewLayout = (ConstraintLayout)findViewById(R.id.webview_layout);
webview = (WebView)findViewById(R.id.webView);
webview.clearCache(true);
webview.clearHistory();
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
startLoadingUrlFromServer();
}
private void startLoadingUrlFromServer() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, kAppUrl,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finishLoadindDataFromServerWithData(response);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
openWebSite(null);
}
});
}
});
queue.add(stringRequest);
}
private void finishLoadindDataFromServerWithData(String response) {
if (response == null || response.equals("")) {
openWebSite(null);
return;
}
if (!response.startsWith("http://") && !response.startsWith("https://")) {
openWebSite(null);
return;
}
openWebSite(response);
}
private void openWebSite(String url) {
loadingLayout.setVisibility(View.GONE);
webviewLayout.setVisibility(View.VISIBLE);
if (url == null || url.equals("")) {
webview.loadUrl(kDefaultAppUrl);
} else {
webview.loadUrl(url);
}
}
The problem that when I set the Visibility of loadingLayout to GONE and the webviewLayout to VISIBLE the app has a white background for two seconds, Any idea how I can change this background color?
It looks like the color you are finding for two seconds is the application theme background.
Go to your AndroidManifest.xml file and open the theme your Application tag is having (if another theme is defined in Activity tag, open that).
This should open your styles.xml file. Add new item for windowBackground to your AppTheme (Assuming this is your theme name), This will change the white background color to the defined one (in below code, its black).
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">#android:color/black</item>
...
..
.
</style>
</resources>
I have been trying to implement splash Screen to my app with help of many codes avaible in sites , but none worked for me.
Each time the app is crashing after displaying splash screen for 3 secs.
I don't know where i'm going wrong , please make corrections to my code to display splash screen correctly ! Thank You !
//This is my Main activity
1. public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button) this.findViewById(R.id.gg);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.gg);
one.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Good Game", Toast.LENGTH_SHORT).show();
mp1.start();
}
});
Button two = (Button) this.findViewById(R.id.gm);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.gm);
two.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Oh, They got me!", Toast.LENGTH_SHORT).show();
mp2.start();
}
});
Button three = (Button) this.findViewById(R.id.cb);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.cb);
three.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Come on boy", Toast.LENGTH_SHORT).show();
mp3.start();
}
});
Button four = (Button) this.findViewById(R.id.ns);
final MediaPlayer mp4 = MediaPlayer.create(this, R.raw.ns);
four.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Nice shot", Toast.LENGTH_SHORT).show();
mp4.start();
}
});
Button five = (Button) this.findViewById(R.id.wp);
final MediaPlayer mp5 = MediaPlayer.create(this, R.raw.wp);
five.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You wanna piece of me!", Toast.LENGTH_SHORT).show();
mp5.start();
}
});
Button six = (Button) this.findViewById(R.id.bi);
final MediaPlayer mp6 = MediaPlayer.create(this, R.raw.bi);
six.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Bring it", Toast.LENGTH_SHORT).show();
mp6.start();
}
});
Button seven = (Button) this.findViewById(R.id.lg);
final MediaPlayer mp7 = MediaPlayer.create(this, R.raw.lg);
seven.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Let’s go, Yeah!", Toast.LENGTH_SHORT).show();
mp7.start();
}
});
Button eight = (Button) this.findViewById(R.id.ru);
final MediaPlayer mp8 = MediaPlayer.create(this, R.raw.ru);
eight.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Ready Up", Toast.LENGTH_SHORT).show();
mp8.start();
}
});
Button nine = (Button) this.findViewById(R.id.nn);
final MediaPlayer mp9 = MediaPlayer.create(this, R.raw.nn);
nine.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Nooooo", Toast.LENGTH_SHORT).show();
mp9.start();
}
});
Button ten = (Button) this.findViewById(R.id.cm);
final MediaPlayer mp10 = MediaPlayer.create(this, R.raw.cm);
ten.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Cover me", Toast.LENGTH_SHORT).show();
mp10.start();
}
});
Button eleven = (Button) this.findViewById(R.id.hh);
final MediaPlayer mp11 = MediaPlayer.create(this, R.raw.hh);
eleven.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Hoo-ya", Toast.LENGTH_SHORT).show();
mp11.start();
}
});
Button twelve = (Button) this.findViewById(R.id.mo);
final MediaPlayer mp12 = MediaPlayer.create(this, R.raw.mo);
twelve.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Move out", Toast.LENGTH_SHORT).show();
mp12.start();
}
});
Button thirteen = (Button) this.findViewById(R.id.gs);
final MediaPlayer mp13 = MediaPlayer.create(this, R.raw.gs);
thirteen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Get Some", Toast.LENGTH_SHORT).show();
mp13.start();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Your Messege",Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
//This is my activity_main.xml
2. <android.support.design.widget.CoordinatorLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.android.mmm.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
//This is content_main.xml
3. <android.support.v4.widget.NestedScrollView
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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.android.mmm.MainActivity"
tools:showIn="#layout/activity_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000">
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="GG"
android:id="#+id/gg"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/gm"
android:layout_width="100dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:text="GM"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold"
tools:ignore="HardcodedText" />
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="CB"
android:id="#+id/cb"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="NS"
android:id="#+id/ns"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="WP"
android:id="#+id/wp"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="BI"
android:id="#+id/bi"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="LG"
android:id="#+id/lg"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="RU"
android:id="#+id/ru"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="NN"
android:id="#+id/nn"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="CM"
android:id="#+id/cm"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="HH"
android:id="#+id/hh"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="MO"
android:id="#+id/mo"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="GS"
android:id="#+id/gs"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
//This is AndroidManifest.xml
4. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.mmm">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
//This is styles.xml
5. <resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
//This is my SplashActivity.Java
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
6. //This is activity_splash.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/wwe_logo" />
</RelativeLayout>
AppCompatActivity has it's own toolbar so you need to remove it by using android:theme="#style/AppTheme.NoActionBar" in manifest
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
</activity>
Although if you are not doing much customization in your toolbar then your can also skip creating your own toolbar by removing it from XML and removing it's initialization from java code as well but by doing this , you will lose the feature of collapsing toolbar
Making a splash screen is actually pretty easy.
1. Create drawable
In my case, I created a drawable named splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:opacity="opaque">
<item android:drawable="#color/colorWhite" />
<item>
<bitmap
android:gravity="center"
android:src="#drawable/sensesmart_icon" />
</item>
2. Add drawable to your styles.xml
Here I just added my drawable to styles:
<style name="SplashTheme" parent="AppTheme">
<item name="android:windowBackground">#drawable/splash</item>
</style>
3. Add splash to manifest
You want to actually tell your app that the splash layout should show before the app has loaded:
<activity android:name=".BaseActivity"
android:screenOrientation="portrait"
android:theme="#style/SplashTheme"> <!--Splash screen-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
4. Set theme on your starting activity
In my case, BaseActivity is the activity which starts my application, so inside my onCreate(), I start with setting my theme:
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_base);
super.onCreate(savedInstanceState);
}
This is the only thing you need to do. If you use this method, the splash screen doesn't stay for longer than it needs. Your contentView will start as soon as you have loaded your app.
Hope this helps!
Right now my goal is to have the Colors activity allow users to hit a button to change the color they are drawing with. How do I get the instance of the canvas in my activity_main.xml to my Colors activity so I can change the color that is drawn on it?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09B8C1"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.app.MainActivity">
<com.app.color.DrawingView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/drawing"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#FFFFFFFF"
android:layout_above="#+id/settings"
android:layout_alignParentTop="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="changeColor"
android:text="#string/Settings"
android:id="#+id/settings"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/button5"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="clearScreen" />
</RelativeLayout>
MainActivity.java
package com.app.color;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
DrawingView dv = new DrawingView();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeColor(View view)
{
Intent intent = new Intent(MainActivity.this, Colors.class);
startActivity(intent);
}
public void clearScreen(View view)
{
}
}
Colors.java
package com.app.color;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Colors extends AppCompatActivity {
DrawingView dv = new DrawingView(,);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
}
public void toWhite(View view)
{
dv.setColor("#ffffff");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
public void toYellow(View view)
{
dv.setColor("#ffff00");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
public void toBlue(View view)
{
dv.setColor("#0000ff");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
public void toRed(View view)
{
dv.setColor("#ff0000");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
public void toGreen(View view)
{
dv.setColor("#00ff00");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
public void toBlack(View view)
{
dv.setColor("#00000");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
}
DrawingView.java
package com.app.color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawingView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Get the coordinates of the touch event.
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
// Makes our view repaint and call onDraw
invalidate();
return true;
}
public void setColor(String newColor){
invalidate();
int paintColor = Color.parseColor(newColor);
paint.setColor(paintColor);
}
}
activity_colors.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.app.Colors">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Choose Color"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_below="#+id/textView"
android:onClick="toWhite"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:text="#string/white" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:onClick="toBlue"
android:layout_alignRight="#+id/button"
android:layout_alignEnd="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#153fc7"
android:text="#string/blue" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/red"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:onClick="toRed"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#f01010" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/yellow"
android:id="#+id/button4"
android:background="#f7e80f"
android:layout_below="#+id/button3"
android:onClick="toYellow"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/button3"
android:layout_alignEnd="#+id/button3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Green"
android:id="#+id/button6"
android:layout_below="#+id/button4"
android:onClick="toGreen"
android:layout_alignRight="#+id/button4"
android:layout_alignEnd="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#00ff00" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Black"
android:id="#+id/button7"
android:layout_below="#+id/button6"
android:background="#000000"
android:onClick="toBlack"
android:textColor="#ffffff"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
My understanding is that, you want to change the color of DrawingView view on any event (ex: button click).
For that please follow the below code :
Firstly, create the attribute styles in attrs.xml
<declare-styleable name="DrawingView">
<!-- drawing view color attributes -->
<attr name="dv_background_color" format="color" />
<attr name="dv_foreground_color" format="color" />
<!-- You can add other custom attributes also -->
<attr name="dv_padding" format="dimension" />
<attr name="dv_width" format="dimension" />
</declare-styleable>
Now write the below code in your java class file :
public class DrawingView extends View {
//Default colors
private int mDrawingViewBackgroundColor = 0xFF0000FF;
private int mDrawingViewForegroundColor = 0xFF0000FF;
//Default padding
private int mViewPadding = 5;
private int mViewWidth = 10;
private Paint mForeGroundColorPaint = new Paint();
private Path mBackGroundColorPaint = new Path();
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typeArr = context.obtainStyledAttributes(attrs, R.styleable.DrawingView);
try {
//Inflate all the attributes of DrawingView from xml that are initialize in activity_main.xml layout file.
mDrawingViewBackgroundColor = typeArr.getColor(R.styleable.DrawingView_dv_background_color, mDrawingViewBackgroundColor);
mDrawingViewForegroundColor = (R.styleable.DrawingView_dv_background_color, mDrawingViewForegroundColor);
mViewPadding = (int)typeArr.getDimension(R.styleable.DrawingView_dv_padding, mViewPadding);
mViewWidth = (int)typeArr.getDimension(R.styleable.DrawingView_dv_width, mViewWidth);
}finally {
typeArr.recycle();
}
setupPaints();
}
setupPaints() {
//Render DrawingView colors - Foreground color
mForeGroundColorPaint.setColor(mDrawingViewForegroundColor);
mForeGroundColorPaint.setAntiAlias(true);
mForeGroundColorPaint.setStrokeWidth(5f);
mForeGroundColorPaint.setStyle(Paint.Style.STROKE);
mForeGroundColorPaint.setStrokeJoin(Paint.Join.ROUND);
//Render DrawingView colors - Background color
mBackGroundColorPaint.setColor(mDrawingViewBackgroundColor);
mBackGroundColorPaint.setAntiAlias(true);
mBackGroundColorPaint.setStrokeWidth(5f);
mBackGroundColorPaint.setStyle(Paint.Style.STROKE);
mBackGroundColorPaint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
public void invalidate() {
setupPaints();
super.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}