Lottie Animation not working with setExitSharedElementCallback android - java

I am working on Android with a Lottie animation. I implemented a shared transition on Lottie from one activity to another activity. But this is not Working. What am I doing wrong in my setExitSharedElementCallback method?
MainActivity.java
package com.example.trans;
import android.app.ActivityOptions;
import android.app.SharedElementCallback;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import com.airbnb.lottie.LottieAnimationView;
public class MainActivity extends AppCompatActivity {
LottieAnimationView lottieAnimationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lottieAnimationView = findViewById(R.id.animation_logo);
setExitSharedElementCallback(new SharedElementCallback() {
#Override
public Parcelable onCaptureSharedElementSnapshot(View sharedElement, Matrix viewToGlobalMatrix, RectF screenBounds) {
int bitmapWidth = Math.round(screenBounds.width());
int bitmapHeight = Math.round(screenBounds.height());
Bitmap bitmap = null;
if (bitmapWidth > 0 && bitmapHeight > 0) {
Matrix matrix = new Matrix();
matrix.set(viewToGlobalMatrix);
matrix.postTranslate(-screenBounds.left, -screenBounds.top);
bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.concat(matrix);
sharedElement.draw(canvas);
}
return bitmap;
}
});
findViewById(R.id.start_animation).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, lottieAnimationView, "simple_activity_transition");
startActivity(intent, options.toBundle());
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#000"
tools:context=".MainActivity">
<Button
android:id="#+id/start_animation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/animation_logo"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="click Me" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/animation_logo"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:transitionName="simple_activity_transition"
app:lottie_autoPlay="true"
app:lottie_loop="false"
app:lottie_rawRes="#raw/dm"
app:lottie_renderMode="hardware"
app:lottie_speed="1.2"
tools:ignore="MissingConstraints" />
</RelativeLayout>
activityMain2.java
package com.example.trans;
import androidx.appcompat.app.AppCompatActivity;
import android.app.SharedElementCallback;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageView;
import com.airbnb.lottie.LottieAnimationView;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setEnterSharedElementCallback(new SharedElementCallback() {
#Override
public View onCreateSnapshotView(Context context, Parcelable snapshot) {
View view = new View(context);
view.setBackground(new BitmapDrawable((Bitmap) snapshot));
return view;
}
#Override
public void onSharedElementStart(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = findViewById(R.id.animation_logo);
for (int i = 0; i < sharedElements.size(); i++) {
if (sharedElements.get(i) == sharedElement) {
View snapshot = sharedElementSnapshots.get(i);
Drawable snapshotDrawable = snapshot.getBackground();
sharedElement.setBackground(snapshotDrawable);
sharedElement.setImageAlpha(0);
forceSharedElementLayout();
break;
}
}
}
private void forceSharedElementLayout() {
ImageView sharedElement = findViewById(R.id.animation_logo);
int widthSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getWidth(),
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getHeight(),
View.MeasureSpec.EXACTLY);
int left = sharedElement.getLeft();
int top = sharedElement.getTop();
int right = sharedElement.getRight();
int bottom = sharedElement.getBottom();
sharedElement.measure(widthSpec, heightSpec);
sharedElement.layout(left, top, right, bottom);
}
#Override
public void onSharedElementEnd(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = findViewById(R.id.animation_logo);
sharedElement.setBackground(null);
sharedElement.setImageAlpha(255);
}
});
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#000"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/animation_logo"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:transitionName="simple_activity_transition"
app:lottie_autoPlay="true"
app:lottie_loop="false"
app:lottie_rawRes="#raw/dm"
app:lottie_renderMode="hardware"
app:lottie_speed="1.2" />
</RelativeLayout>
Styles
<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>
<item name="android:windowSharedElementEnterTransition">#android:transition/explode</item>
</style>

Related

Android Studio ImageView and Bitmap

An activity has an icon to choose Image from Files. After choosing the Image, The next activity page opens which has A button and an ImageView where the selected iimage should be displayed.
I can choose the Image but it does not show on ImageView.
I has tried Bitmap and it doesnt work. If I try to resize map and then run app, after choosing the image the app closes.
Below is the XML and Java of the activity
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ShowPhotoActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="196dp"
android:layout_height="219dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.414"
tools:srcCompat="#tools:sample/avatars" />
<Button
android:id="#+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EDIT PHOTO"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.773" />
</androidx.constraintlayout.widget.ConstraintLayout>
//Java of the Activity.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
public class ShowPhotoActivity extends AppCompatActivity {
ImageView myImage;
Button btnEdit;
String path = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_photo);
myImage = (ImageView) findViewById(R.id.imageView);
btnEdit = findViewById(R.id.btnEdit);
path = getIntent().getExtras().getString("path");
File imgFile = new File(path);
if (imgFile.exists()) {
Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//myImage.setImageBitmap(Bitmap.createScaledBitmap(b, 40, 40, false));
myImage.setImageBitmap(b);
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShowPhotoActivity.this, EditPhotoActivity.class);
intent.putExtra("path", path);
startActivity(intent);
}
});
}
}
public static Bitmap RotateBitmat(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
}
I need the selected Image to be shown in the ImageView and when I click the Edit button the Image should be passed to the next activity too.

How to implement SelectionTracker in Java not Kotlin

On Android, I want to users to be able to select multiple rows from a list. I read that I can use SelectionTracker with a RecyclerView to enable list-item selection.
But all the code examples are in Kotlin. Are there any examples of SelectionTracker in Java?
Here is a settings menu that allows the user to choose multiple settings. To begin the selection, the user has to long press any setting. Then they can tap any setting to choose more.
Activity
package com.locuslabs.android.sdk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.locuslabs.android.sdk.api.ConfigurationExperiments;
import com.locuslabs.android.sdk.api.MapExperiments;
import com.locuslabs.android.sdk.api.MapViewExperiments;
import com.locuslabs.android.sdk.api.PositionExperiments;
import com.locuslabs.android.sdk.api.VenueExperiments;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class SettingsActivity extends Activity {
private static final String TAG = "SettingsActivity";
SelectionTracker<Long> selectedSettingTracker;
private RecyclerView settingsRecyclerView;
private List<String> listOfUsableApis;
private ApiSettings mApiSettings;
private void setApiSettings(List<String> settingNamesSelected) {
for (String settingName : settingNamesSelected) {
if (settingName.equals(getResources().getString(R.string.api_setting_draw_line)))
mApiSettings.mDrawLine = true;
if (settingName.equals(getResources().getString(R.string.api_setting_search)))
mApiSettings.mLogSearch = true;
/* omitted rest of options for brevity */
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApiSettings = new ApiSettings();
setContentView(R.layout.activity_settings);
settingsRecyclerView = findViewById(R.id.settingsRecyclerView);
settingsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Button backButton = findViewById(R.id.settings_back_button);
Button saveButton = findViewById(R.id.settings_apply_button);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setApiSettings(getSettingNamesSelected());
Intent intent = new Intent();
intent.putExtra("apiSettings", new Gson().toJson(mApiSettings));
setResult(RESULT_OK, intent);
finish();
}
});
listOfUsableApis = /* omitted for brevity */
final SettingsAdapter settingsAdapter = new SettingsAdapter();
settingsRecyclerView.setAdapter(settingsAdapter);
// Handle selection of settings
selectedSettingTracker = new SelectionTracker.Builder<Long>(
"selectedSettingTrackerId",
settingsRecyclerView,
new StableIdKeyProvider(settingsRecyclerView),
new SettingsDetailsLookup(),
StorageStrategy.createLongStorage()
).
withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).
build();
}
private List<String> getSettingNamesSelected() {
Selection<Long> settingsSelection = selectedSettingTracker.getSelection();
Iterator<Long> settingSelectionIterator = settingsSelection.iterator();
List<String> settingNamesSelected = new ArrayList<>();
while (settingSelectionIterator.hasNext()) {
Long settingSelectionId = settingSelectionIterator.next();
String settingNameSelected = listOfUsableApis.get(settingSelectionId.intValue());
settingNamesSelected.add(settingNameSelected);
}
return settingNamesSelected;
}
public static class ApiSettings {
public boolean mDrawLine = false;
public boolean mWalkSimulator = false;
/* omitted most options for brevity */
public ApiSettings() {
}
}
private class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.SettingViewHolder> {
public SettingsAdapter() {
setHasStableIds(true);
}
#NonNull
#Override
public SettingViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
TextView textView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.setting_list_item, parent, false);
SettingViewHolder settingViewHolder = new SettingViewHolder(textView);
return settingViewHolder;
}
#Override
public void onBindViewHolder(#NonNull SettingViewHolder holder, final int position) {
holder.textView.setText(listOfUsableApis.get(position));
holder.textView.setActivated(selectedSettingTracker.isSelected((long) position));
holder.position = position;
}
#Override
public int getItemCount() {
return listOfUsableApis.size();
}
#Override
public long getItemId(int position) {
return Long.valueOf(position);
}
public class SettingViewHolder extends RecyclerView.ViewHolder {
public int position;
public TextView textView;
public SettingViewHolder(TextView v) {
super(v);
textView = v;
}
}
}
private class SettingsDetailsLookup extends ItemDetailsLookup<Long> {
#Nullable
#Override
public ItemDetails<Long> getItemDetails(#NonNull MotionEvent event) {
View view = settingsRecyclerView.findChildViewUnder(event.getX(), event.getY());
if (view != null) {
final RecyclerView.ViewHolder viewHolder = settingsRecyclerView.getChildViewHolder(view);
if (viewHolder instanceof SettingsAdapter.SettingViewHolder) {
final SettingsAdapter.SettingViewHolder settingViewHolder = (SettingsAdapter.SettingViewHolder) viewHolder;
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return viewHolder.getAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return Long.valueOf(settingViewHolder.position);
}
};
}
}
return null;
}
}
}
Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#454545"
android:weightSum="100">
<Button
android:id="#+id/settings_back_button"
android:background="#454545"
android:drawableStart="#drawable/arrow_white"
android:drawableLeft="#drawable/arrow_white"
android:layout_gravity="start"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="90"
/>
<Button
android:id="#+id/settings_apply_button"
android:background="#454545"
android:drawableStart="#android:drawable/ic_menu_save"
android:drawableLeft="#android:drawable/ic_menu_save"
android:layout_gravity="end"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long-press for first setting, then tap other settings for multiple selection"
app:layout_constraintBottom_toTopOf="#+id/settingsRecyclerView"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/settingsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
</LinearLayout>
Layout setting_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/setting_list_item_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/setting_background"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
Background drawable setting_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark" android:state_activated="true" />
<item android:drawable="#android:color/white" />
</selector>
References:
https://developer.android.com/guide/topics/ui/layout/recyclerview#select This documentation is hard to read. It needs an example.
https://proandroiddev.com/a-guide-to-recyclerview-selection-3ed9f2381504 Hard to read Kotlin example
https://www.youtube.com/watch?v=jdKUm8tGogw&feature=youtu.be&list=PLWz5rJ2EKKc9Gq6FEnSXClhYkWAStbwlC&t=980 Google IO intro to this feature (but in Kotlin)
https://medium.com/#Dalvin/android-recycler-view-with-multiple-item-selections-b2af90eb5825 Another Java example!

How to make a fixed BottomNavigationView with title below, no shifted navigation

I am having difficulties in making fixed BottomNavigationView like in the Photo below: OriginalPhoto.png
Here is my own project's BottomNavigationView: MyPhoto.png
Also, I want the title below icons visible all the time, not just when clicked. How can I do this??
Note: I have read all stackoverflow articles and followed other external links but no tangible results have gained. Please help me to figure this subtle problem out. Would be better if only with XML to solve this problem, rather than java code.
Here is my source code for activity_menu.xml, btw, it is not activity_main.xml because i have used main activity for my login page. This activity is after login page: `
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="datasite.com.konnex.Menu"
android:background="#ffffff">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3fc0ea">
<ImageButton
android:layout_width="120dp"
android:layout_height="38dp"
android:background="#drawable/lg1"
android:layout_marginLeft="130dp"
android:layout_marginStart="130dp"/>
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginStart="90dp"/>
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2">
<FrameLayout
android:layout_width="191dp"
android:layout_height="150dp"
android:id="#+id/fm_cases"
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/cases"
android:layout_marginLeft="50dp"
android:layout_marginStart="50dp"
android:layout_marginTop="35dp"
android:id="#+id/img_cases" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cases"
android:layout_marginLeft="70dp"
android:layout_marginStart="70dp"
android:layout_marginTop="128dp"
android:textSize="18sp"
android:textColor="#424242"/>
<TextView
android:layout_width="22dp"
android:layout_height="wrap_content"
android:text="#string/string_1"
android:textColor="#FFFFFF"
android:textSize="17sp"
android:layout_marginLeft="122dp"
android:layout_marginStart="122dp"
android:layout_marginTop="35dp"
android:background="#E91E63"
android:id="#+id/notif_cases"/>
</FrameLayout>
</GridLayout>
</RelativeLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fffafa"
app:menu="#menu/navigation"
app:itemIconTint="#color/dark"
app:itemTextColor="#color/dark"
android:animateLayoutChanges="false"
android:splitMotionEvents="false"
android:fitsSystemWindows="true"/>
</LinearLayout>`
Here is the source code for menu.java. it is also after main.java activity which is for login used.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
public class Menu extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
return true;
case R.id.nav_location:
return true;
case R.id.nav_phone:
return true;
case R.id.nav_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FrameLayout fml = (FrameLayout) findViewById(R.id.fm_cases);
fml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Menu.this, Cases.class);
startActivity(i);
}
});
}
}
Thank you in advance!!! I really need your help Guys)
My Navigation.xml:
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_about" />
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
android:title="#string/title_location"
/>
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
android:title="#string/title_phone"
/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home"
/>
</menu>
Try using AHBottomNavigation library, I suggest this because is has simple implementation considering your case and reduces your work to create another menu.xml file and handling menu option methods in your code. Just add this line in your gradle file.
compile 'com.aurelhubert:ahbottomnavigation:2.0.6'
It will take care of the layout issue you have moreover, it has lots of customization options. You can read further here, but for your case the simple use to keep titles is..
public class MyActivity extends AppCompatActivity{
#BindView(R.id.bottom_navigationbar)
AHBottomNavigation bottomNavigation;
onCreate(){
bottomNavigation.addItem(new AHBottomNavigationItem("Title1", iconID1);
bottomNavigation.addItem(new AHBottomNavigationItem("Title2", iconID2);
bottomNavigation.addItem(new AHBottomNavigationItem("Title3", iconID3);
bottomNavigation.addItem(new AHBottomNavigationItem("Title4", iconID4);
bottomNavigation.setAccentColor(ContextCompat.getColor(this, themeColor));
//will always show titles
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
}}
setUpClickListener.
bottomNavigation.setOnTabSelectedListener((position, wasSelected) -> {
if (position == 0 && !wasSelected) {
} else if (position == 1 && !wasSelected) {
} else if (position == 2 && !wasSelected) {
} else if (position == 3 && !wasSelected) {
} else if (position == 4 && !wasSelected) {
}
return true;
}
);
Ok then try to add app:showAsAction in menu item
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
app:showAsAction="ifRoom"
android:title="#string/title_about" />
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
app:showAsAction="ifRoom"
android:title="#string/title_location"
/>
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
app:showAsAction="ifRoom"
android:title="#string/title_phone"
/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
app:showAsAction="ifRoom"
android:title="#string/title_home"
/>
</menu>
If your problem not resolve then replace this one showAsAction="always|withText"
after then you can use this method for disabling shifted menu
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
Updated Menu.java: `package datasite.com.konnex;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.reflect.Field;
public class Menu extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
return true;
case R.id.nav_location:
return true;
case R.id.nav_phone:
return true;
case R.id.nav_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//Add This
disableShiftMode((BottomNavigationView)findViewById(R.id.navigation))
FrameLayout fml = (FrameLayout) findViewById(R.id.fm_cases);
fml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Menu.this, Cases.class);
startActivity(i);
}
});
}
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
}
Updated Navigation.xml:
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/title_about"
app:showAsAction="always|withText"/>
<item
android:id="#+id/nav_location"
android:icon="#drawable/nav_location"
android:title="#string/title_location"
app:showAsAction="always|withText" />
<item
android:id="#+id/nav_phone"
android:icon="#drawable/nav_call"
android:title="#string/title_phone"
app:showAsAction="always|withText"/>
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/title_home"
app:showAsAction="always|withText" />
</menu>
`

How to randomly rotate an image in Android?

I'm new at Android Programing and I want to know how to rotate an image by a random angle. I need this for my "Spin the Bottle" game. Here is my code so far:
package example.com.bottlegame;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.RotateDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Object;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
ImageView spin,bottle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin = (ImageView) findViewById(R.id.ivSpin);
bottle = (ImageView) findViewById(R.id.ivBottle);
final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.roatate);
spin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottle.startAnimation(animRotate);
}
});
}
}
Now I'm rotating an image with XML, but can you help me to rotate it with just Java code. Here is the XML code in anim folder:
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/linear_interpolator">
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:pivotX="50%"
android:pivotY="50%"
android:fromDegrees="0"
android:toDegrees="360"
android:drawable="#drawable/bottle"
android:duration="1000"
android:repeatCount="1"
android:repeatMode="reverse"
android:startOffset="0"
/>
</set>`
And here is the activity_main.xml:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/bg_background">
<ImageView
android:layout_width="wrap_content"
android:layout_height="100sp"
android:layout_centerHorizontal="true"
android:id="#+id/ivSpin"
android:src="#drawable/spin_up"
android:layout_marginTop="400sp"
android:contentDescription="#string/spin"
/>
<ImageView
android:layout_width="65sp"
android:layout_height="200sp"
android:id="#+id/ivBottle"
android:src="#drawable/bottle"
android:layout_marginTop="80dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:contentDescription="#string/bottle"
/>
</RelativeLayout>
You can easily configure your animation in Java code as well as in xml. For your case you could use class RotateAnimation and its' constructor public RotateAnimation(float fromDegrees, float toDegrees, float pivotX, float pivotY)
So, try somehting like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin = (ImageView) findViewById(R.id.ivSpin);
bottle = (ImageView) findViewById(R.id.ivBottle);
float toDegrees = new Random().nextFloat() * Integer.MAX_VALUE % 360;
final Animation animRotate = new RotateAnimation(0, toDegrees, 50, 50);
animRotate.setDuration(1000);
animRotate.setRepeatCount(1);
animRotate.setRepeatMode(Animation.REVERSE);
spin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottle.startAnimation(animRotate);
}
});
}
I think, that no comments are required.

image cannot be resolved or is not a field

I am doing an android project to create an animation using eclipse.
On MainActivity.java
it compiler shows 5 lint errors as follows
-image cannot be resolved or is not a field
-activity_main cannot be resolved or is not a field
-translate cannot be resolved or is not a field
-rotate cannot be resolved or is not a field
-shape cannot be resolved or is not a field
Here is doing there my code in MainActivity.java
package ahmed103.appdemo;
import android.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.*;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements AnimationListener {
ImageView image;
Animation animation1;
Animation animation2;
Button rotate, translate;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
rotate = (Button) findViewById(R.id.rotate);
translate = (Button) findViewById(R.id.translate);
image.setImageResource(R.drawable.shape);
animation1 = AnimationUtils.loadAnimation(this, R.anim.rotate);
animation2 = AnimationUtils.loadAnimation(this, R.anim.translate);
userInputHandler();
}
private void userInputHandler() {
rotate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
image.startAnimation(animation1);
}
});
translate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
image.startAnimation(animation2);
}
});
}
#Override
public void onAnimationEnd(Animation animation) {
image.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
image.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationStart(Animation animation) {
image.setVisibility(View.VISIBLE);
}
}
Here is down there my activity_main.xml file
<html>
<LinearLayout 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="#DCDCDC"
android:orientation="vertical"
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=".MainActivity" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="70dp"
android:minHeight="150dp"
android:minWidth="150dp" />
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableRow>
<Button
android:id="#+id/rotate"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_weight="1"
android:text="#string/rotate_text" />
<Button
android:id="#+id/translate"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_weight="1"
android:text="#string/translate_text" />
</LinearLayout>
</html>
Remove the below import
import android.R;
Also you have
<html> and </html>// should be removed from xml
Imnport
import ahmed103.appdemo.R;
And use
<?xml version="1.0" encoding="utf-8"?>
as the first statement in your activity_main.xml

Categories