I tried to add Lottie Animation to Java (Android) programmatically, but I keep failing. I will show my code below I need to change from drawable to Lottie.
This is the code for drawables:
if (status.equals("connect")) {
vpnBtn.setBackgroundResource(R.drawable.but_connect_light);
logTv.setTextColor(getResources().getColor(R.color.font_color));
} else if (status.equals("connecting")) {
vpnBtn.setBackgroundResource(R.drawable.but_connecting_dark);
logTv.setTextColor(getResources().getColor(R.color.font_color));
} else if (status.equals("connected")) {
vpnBtn.setBackgroundResource(R.drawable.but_disconnect_dark);
logTv.setTextColor(getResources().getColor(R.color.purple));
} else if (status.equals("failed")) {
vpnBtn.setBackgroundResource(R.drawable.but_connect_dark);
}
This is the xml relating above
<ImageView
android:id="@+id/vpnBtn"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:tag="1"
android:layout_width="140dp"
android:layout_height="140dp"
android:background="@drawable/but_connect_light"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"/>
I achieved this with the solution below:
String vpnsBtn;
if (check.equals("night")){
switch (status) {
case "connect":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("disconnected.json");
logTv.setTextColor(getResources().getColor(R.color.font_color));
break;
case "connecting":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("connectingg.json");
logTv.setTextColor(getResources().getColor(R.color.font_color));
break;
case "connected":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("connected.json");
logTv.setTextColor(getResources().getColor(R.color.purple));
break;
case "failed":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("disconnected.json");
break;
}
}else {
switch (status) {
case "connect":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("disconnected.json");
logTv.setTextColor(getResources().getColor(R.color.font_color));
break;
case "connecting":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("connectingg.json");
logTv.setTextColor(getResources().getColor(R.color.font_color));
break;
case "connected":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("connected.json");
logTv.setTextColor(getResources().getColor(R.color.purple));
break;
case "failed":
vpnBtn.setVisibility(View.VISIBLE);
vpnsBtn = ("disconnected.json");
break;
}
}
LottieAnimationView animationView = findViewById(R.id.vpnBtn);
animationView.setImageAssetsFolder("vpnconnect");
animationView.setAnimation(vpnsBtn);
animationView.loop(true);
animationView.playAnimation();
I hope this will help others who want to use dynamic buttons with Lottie on Android.