why my splash screen is so long - android

I'm trying to implement a splash screen on my app. After the loading of the splash screen, I have two issues.
If the user is connected, an activity is started. If not, an other is started.
But, with my implementation, when the user is connected, the splash screen is very long (8 or 9 sec), but I don't know why.
That is my first class which check if the user is connected, and it load some shared preferences? So maybe it's that?
public class AnnaActivity extends AppCompatActivity {
public PrefManager pref;
private AllRequest req;
private static final String REQUEST_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.pref = new PrefManager(getApplicationContext());
boolean isco = pref.getIsConnect();
if (isco) {
Log.e("SPLASH", "IsConnected");
Intent loginActivity = new Intent(this, NavigationDrawerActivity.class);
startActivity(loginActivity);
finish();
} else {
Log.e("SPLASH", "launch login activity");
Intent loginActivity = new Intent(this, MainActivity.class);
startActivity(loginActivity);
finish();
}
}
}
that is my splash drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryDark"/>
<item android:bottom="8dp"
android:top="8dp"
android:left="8dp"
android:right="8dp">
<bitmap android:gravity="center"
android:src="#mipmap/ic_launcher"
android:antialias="true"/>
</item>
</layer-list>
And my splach style
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_drawable</item>
</style>
(Edit post) The navigation drawerActivity
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Response.Listener, Response.ErrorListener{
public TextView TextViewEmailAddress;
public TextView TextViewLogin;
private PrefManager pref;
private AllRequest req;
public RequestQueue mQueue;
private static final String REQUEST_TAG = "LogOutActivity";
private String address;
private String login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
this.TextViewEmailAddress = (TextView)header.findViewById(R.id.textView_drawer_mail);
this.TextViewLogin = (TextView)header.findViewById(R.id.textView_drawer_login);
this.pref = new PrefManager(getApplicationContext());
this.req = new AllRequest(getApplicationContext());
this.mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
address = this.pref.getEmail();
login = this.pref.getLogin();
this.TextViewEmailAddress.setText(address);
this.TextViewLogin.setText(getText(R.string.text_view_login_drawer) + " " + login);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_mon_compte) {
Intent intent = new Intent(NavigationDrawerActivity.this, MyAccountActivity.class);
startActivity(intent);
} else if (id == R.id.nav_deconnection) {
deconnexion();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void deconnexion(){
LayoutInflater factory = LayoutInflater.from(this);
final View alertDialogView = factory.inflate(R.layout.alertdialog_logout, null);
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(alertDialogView);
adb.setTitle(R.string.alertDialod_logout_Title);
adb.setPositiveButton((R.string.alertDialog_logout_PositiveBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String accessToken = pref.getAccessToken();
req.revokeTokenRequest(REQUEST_TAG, accessToken, NavigationDrawerActivity.this, NavigationDrawerActivity.this);
pref.logout();
Intent intent = new Intent(NavigationDrawerActivity.this, MainActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton((R.string.alertDialog_logout_NegativeBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("errrrrrror :(", "it's not working");
}
#Override
public void onResponse(Object response) {
Log.e("pololololo","it's working :D");
}
}

Related

I have added profile activity, then added a dynamic image profile and username. After i did that, the navigation buttons are not working at all

here is my java code
that is the java code, I have added navigation profile activity then run it after retrieving the image and user name from the firebase. the navigation buttons are no more clickable
public class OwnerDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth OwnerAuth;
private DatabaseReference OwnerRef;
private CircleImageView OwnNavProfileImge;
private TextView OwnNavProfileName;
String currentUserID;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OwnerAuth = FirebaseAuth.getInstance();
OwnerRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = OwnerAuth.getCurrentUser().getUid();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//for the navigation drawer button to open and close
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View navView = navigationView.inflateHeaderView(R.layout.nav_header_owner_drawer);
OwnNavProfileName = (TextView)navView.findViewById(R.id.NavOwnerUserName);
OwnNavProfileImge = (CircleImageView)navView.findViewById(R.id.NavOwnerProfileImage);
OwnerRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists()) {
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
OwnNavProfileName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(OwnerDrawer.this).load(image).placeholder(R.drawable.profile).into(OwnNavProfileImge);
}
else
{
Toast.makeText(OwnerDrawer.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = OwnerAuth.getCurrentUser();
if(currentUser == null)
{
SendUserTologinActivity();
}
else
{
CheckUserExistence();
}
}
// to see if the user validation and his authenticated so if not, the user will be send to the setup activity.
private void CheckUserExistence()
{
final String current_user_id = OwnerAuth.getCurrentUser().getUid();
OwnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(OwnerDrawer.this, OwnerSetup.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserTologinActivity() {
Intent loginIntent = new Intent(OwnerDrawer.this,OwnerLogin.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// To open the menu button
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Home) {
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Profile) {
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Posting_Cars) {
Toast.makeText(this, "Post Cars", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Chat) {
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Edit_profile) {
Toast.makeText(this, "Edit Profile", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.nav_Logout) {
OwnerAuth.signOut();
SendUserTologinActivity();
Toast.makeText(OwnerDrawer.this, "Logged Out Successfull...", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
To receive callbacks when the user taps a list item in the drawer, implement the OnNavigationItemSelectedListener and attach it to your NavigationView by calling setNavigationItemSelectedListener().
You need to attach the navigationView to listener
navigationView.setNavigationItemSelectedListener(this);
Hope this helps.

Getting error in setGridViewItemClickListener and also how can show images from drawable

I have created android app using GridView with ViewPager for images like gallery or small book which have 14 images
am showing all image from URL. i want also help that how can show my image from drawable
GridView got open successfully and i am able to launch the application.
Functionality is also working fine but when I want to open single image from GridView then my app close and showing message that app has stopped and open app again.
Please review my code and guide me how can I solve this problem. Here is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private GridView gridView;
private GridViewAdapter gridViewAdapter;
private ArrayList<String> listImageURLs = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addImageURLs();
gridView = findViewById(R.id.gridView);
gridViewAdapter = new GridViewAdapter(this, listImageURLs);
gridView.setAdapter(gridViewAdapter);
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, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setGridViewItemClickListener();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setGridViewItemClickListener(){
gridView.setOnItemClickListener((parent, view, position, id) -> {
Bundle bundle = new Bundle();
bundle.putInt("position", position);
bundle.putStringArrayList("imageURLs", listImageURLs);
Intent intent = new Intent(this, ImageActivity.class);
intent.putExtras(bundle);
startActivity(intent);
});
}
private void addImageURLs(){
listImageURLs.add("http://i.dailymail.co.uk/i/pix/2016/04/12/23/3319F89C00000578-3536787-image-m-19_1460498410943.jpg");
listImageURLs.add("https://www.w3schools.com/css/img_forest.jpg");
listImageURLs.add("https://www.w3schools.com/css/trolltunga.jpg");
listImageURLs.add("https://www.w3schools.com/css/pineapple.jpg");
listImageURLs.add("https://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg");
listImageURLs.add("https://www.w3schools.com/css/paris.jpg");
listImageURLs.add("https://www.w3schools.com/css/paris.jpg");
listImageURLs.add("https://www.w3schools.com/css/trolltunga.jpg");
listImageURLs.add("https://www.w3schools.com/css/lights600x400.jpg");
listImageURLs.add("http://wallpaper-gallery.net/images/image/image-11.jpg");
listImageURLs.add("http://wallpaper-gallery.net/images/image/image-15.jpg");
listImageURLs.add("http://wallpaper-gallery.net/images/image/image-19.jpg");
listImageURLs.add("https://cdn.spacetelescope.org/archives/images/thumb700x/heic1509a.jpg");
listImageURLs.add("http://wallpaper-gallery.net/images/image/image-12.jpg");
//listImageURLs.addAll(listImageURLs);
}
}
You need to include the ImageActivity in the AndroidManifest.
I have done a similar project with you and I use this way:
private ArrayList<String> urlImage = new ArrayList<>();
Remember, add data to urlImage
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), ShowImageActivity.class);
intent.putExtra(KEY_URL_IMAGE, urlImage);
intent.putExtra(KEY_POSITION, String.valueOf(position));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
In ShowImageActivity:
Intent intent = getIntent();
if (intent.getExtras() != null) {
url = (ArrayList<String>) intent.getExtras().get(KEY_URL_IMAGE);
position = Integer.parseInt(String.valueOf(intent.getExtras().get(KEY_POSITION)));
Toast.makeText(getApplicationContext(), "URL image" + url.get(position) + "position " + position, Toast.LENGTH_LONG).show();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), url));
final ViewPager.LayoutParams layoutParams = new ViewPager.LayoutParams();
layoutParams.width = ViewPager.LayoutParams.MATCH_PARENT;
layoutParams.height = ViewPager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.BOTTOM;
viewPager.setCurrentItem(position);
and show image from drawable
imageView.setImageResource(getImageId(view.getContext(),resourceImage));
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
You are passing OnItemClickListener in the place of context. You need to use the instance of the class like below.
Intent intent = new Intent(MainActivity.this, ImageActivity.class);
Note: If you use this, then it would have the instance of the class it is written in. In your code, you are using this inside an anonymous class of OnItemClickListener
Also, you need to check if you have defined your activity in the manifest file.

I can't navigate to another activity

Android Error I'm a real noob when it comes to Android Studio, and I'm trying to make it so when I click a button in IntroActivity, it will direct me to the FeaturedActivity page, which contains a list and navigation drawer, if that's important. But when I click the first time in the emulator, the app stops, and when I go back and click it again, nothing happens. I have Java Code for both activities. Could someone help me please?
<activity
android:name=".FeaturedActivity"
android:label="#string/title_activity_featured"
android:theme="#style/AppTheme.NoActionBar"></activity>
The first activity
public class IntroActivity extends AppCompatActivity {
Button ComeInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
ComeInButton = (Button) findViewById(R.id.ComeIn);
ComeInButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(IntroActivity.this, FeaturedActivity.class);
startActivity(i);
}
});
}
}
Featured Activity
public class FeaturedActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String [] art_Names;
TypedArray pics;
String[] artist_Names;
String[] desc;
List<RowItem> rowItems;
ListView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_featured);
rowItems=new ArrayList<RowItem>();
art_Names=getResources().getStringArray(R.array.Featured_Arts);
pics=getResources().obtainTypedArray(R.array.Art_Pics);
artist_Names=getResources().getStringArray(R.array.Artist_Names);
desc=getResources().getStringArray(R.array.Descriptions);
for(int i=0;i<art_Names.length;i++){
RowItem item=new RowItem(art_Names[i], pics.getResourceId(i, -1),artist_Names[i],desc[i]);
rowItems.add(item);
}
myListView=(ListView)findViewById(R.id.list);
CustomerAdapter adapter = new CustomerAdapter(this,rowItems);
myListView.setAdapter(adapter);
myListView.setOnClickListener((View.OnClickListener) this);
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, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String art_name=rowItems.get(position).GetArtName();
Toast.makeText(getApplicationContext(),""+art_name,Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.featured, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The question is a little vague on the details, but taking a shot in the dark, did you register FeaturedActivity in the app manifest?
Something like:
<activity
android:name=".FeaturedActivity"
android:label="#string/title_activity_featured"
android:theme="#style/AppTheme">
should be in your AndroidManifest.xml file.
You are probably getting a nice error message in logcat, so please look there :)
I think the crash cause is where you are casting FeaturedActivity to View.OnClickListener inside FeatureActivity#onCreate(). since it does not implement View.OnClickListener, you get ClassCastException and since you do not catch this exception, then your app crashes.
EDIT I meant this line:
public class FeaturedActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myListView.setOnClickListener((View.OnClickListener) this); // this line
}
...
}
EDIT 2 You can fix it by implementing View.OnClickListener in FeatureActivity like this:
public class FeaturedActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myListView.setOnClickListener(this); // cast is not needed anymore
}
#Override
protected void onClick(View v) {
// handle click
}
...
}
By the way, If you want to handle item click for ListView you should use AdapterView#setOnItemClickListener() instead so you get notified when one of the items in ListView is clicked

How to highlight the imagebutton when it is pressed

I want my imagebutton to hightlight it self, as the normal glow effect when a "normal" button is pressed. So i tried to put the image in, but then there is a "gray field" in the back of the image so i made it transparent so only the image will show but then the glow effect disappeared. Is there a solution to this? :)
please see imgur image as a example- Example image here
if it is to "hard" I can live with the gray field behind the image but is it possible then to make it green with the same highlight effect?
Should i put the code in MainActivity or my fragment java?
Fragment java
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
//TextView nya;
//TextView nsp;
TextView tstnr;
#SuppressWarnings("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
view = getActivity().findViewById(R.id.content_frame);
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
//nsp = (TextView) view.findViewById(R.id.nummertestsp);
// tstnr = (TextView) view.findViewById(R.id.numretladd);
// view = getActivity().findViewById(R.id.content_frame);
taframnummer.setVisibility(INVISIBLE);
msgTxt.setVisibility(INVISIBLE);
aonTxt.setVisibility(INVISIBLE);
aoffTxt.setVisibility(INVISIBLE);
rela1txt.setVisibility(INVISIBLE);
rela2txt.setVisibility(INVISIBLE);
sendSMSaoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgrela2);
}
}
);
// return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
Here my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
else if (id == R.id.nav_share) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://hellmertz.se"));
startActivity(browserIntent);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Put the imageView that you want to highlight above a View with bright color and set the visibility of the view equal to View.GONE. Now with your ImageButton
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
myView.setVisibility(View.VISIBLE);
break;
}
case MotionEvent.ACTION_UP:
myView.setVisibility(View.GONE);
break;
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
myView.setVisibility(View.GONE);
break;
}
}
return true;
}
});
You can user selector drawable and have 3 different button drawables for each state. Create these file is drawables folder and add this line to button android:background="#drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="#drawable/camera_button_hold" android:state_pressed="true"/>
<!-- focused -->
<item android:drawable="#drawable/camera_button_hold" android:state_focused="true"/>
<!-- default -->
<item android:drawable="#drawable/camera_button_normal"/>
</selector>
camera_button_hold.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#673ab7"/>
</shape>
camera_button_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="#673ab7"/>
</shape>

How to inflate badge counter in MenuItem using custom LayerDrawable

I was following this article. Unfortunatelly, badge isn't drawn. Of course I changed invalidateOptionsMenu method to supportInvalidateOptionsMenu method.
I was checking the log, step by step and found out that draw method in custom Drawable named BadgeDrawable is never called. Why is that?
I'm trying to use it in AppCompatActivity using Support Design Library version 23.0.1
I saw this answer but it seems to be out of date.
Is there anyone who managed to implement badger counter for MenuItem icon inside android.support.v7.widget.Toolbar?
If the way shown in the article is wrong then could you suggest other way to achieve the result as in example below?:
Here is a setup inside my application:
LayerDrawable XML ic_filter_notifications.xml:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/ic_filter_notification"
android:drawable="#drawable/ic_filter_grey600_18dp"
android:gravity="center"/>
<!-- set a place holder Drawable so android:drawable isn't null -->
<item android:id="#+id/ic_filter_badge"
android:drawable="#drawable/ic_filter_grey600_18dp">
</item>
</layer-list>
Menu that I use in the Toolbar menu_activity_main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cobytu="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/menu_settings"
android:orderInCategory="100"
android:title="#string/menu_settings"
cobytu:showAsAction="never"/>
<item
android:id="#+id/menu_logout"
android:orderInCategory="1000000"
android:title="#string/menu_logout"
cobytu:showAsAction="never"/>
<item
android:id="#+id/action_filter"
android:title="#string/filters"
android:icon="#drawable/ic_filter_notifications"
cobytu:showAsAction="always"/>
<item
android:id="#+id/action_location"
android:icon="#drawable/ic_map_marker_radius_grey600_18dp"
android:title="#string/location"
cobytu:showAsAction="always"/>
</menu>
This is function sets the count int for new BadgeDrawable inside UsefulFunctions class - UsefulFunctions.java:
public class UsefulFunctions {
private Context ctx;
public UsefulFunctions(Context context){
ctx = context;
}
public static void setBadgeCount(Context context, LayerDrawable icon,
int count) {
BadgeDrawable badge;
// Reuse drawable if possible
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_filter_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
Log.d("mTAG", UsefulFunctions.class.getName()
+ " I'm creating new BadgeDrawable!");
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
Log.d("mTAG",
UsefulFunctions.class.getName() + " badge: " + badge.toString()
+ " count: " + count);
icon.setDrawableByLayerId(R.id.ic_filter_badge, badge);
}
}
This is the important scrap of my MainActivity where I invoke BadgeDrawable creation. I also show what's inside onCreate and in onOptionsItemSelected, may be needed - MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DialogFragmentFilters.FiltersRefreshInterface{
public String username;
//CollapsingToolbarLayout
private CollapsingToolbarLayout mCollapsingToolbarLayout;
//Toolbar
private Toolbar mToolbar;
//TabLayout
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
//NavigationDraver
private static final String SELECTED_ITEM_ID = "selected_item_id";
private static final String FIRST_TIME = "first_time";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationView mNavigationView;
private int mSelectedId;
private boolean mUserSawDrawer = false;
private TextView mNavHeaderNameText;
private TextView mNavHeaderEmailText;
private DatabaseHandler db;
private UserFunctions userFunctions;
private AlertDialog.Builder dialogBuilder;
private AlertDialog alertDialog;
private JSONObject jsonLocation = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFunctions = new UserFunctions();
db = new DatabaseHandler(getApplicationContext());
username = db.getUserDetails().get(DatabaseHandler.getKEY_USER_LOGIN());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setupToolbar();
setupTablayout();
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
View header = LayoutInflater.from(MainActivity.this).inflate(R.layout.nav_header, null);
mNavHeaderNameText = (TextView) header.findViewById(R.id.tv_nav_header_name);
mNavHeaderNameText.setText("Siema "+username+"!");
mNavHeaderEmailText = (TextView) header.findViewById(R.id.tv_nav_header_email);
mNavHeaderEmailText.setText(db.getUserDetails().get(DatabaseHandler.getKEY_USER_EMAIL()));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (!didUserSeeDrawer()) {
showDrawer();
markDrawerSeen();
} else {
hideDrawer();
}
mSelectedId = savedInstanceState == null ? R.id.navigation_item_4 : savedInstanceState.getInt(SELECTED_ITEM_ID);
navigate(mSelectedId);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(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();
showActionDialog(id);
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.menu_settings:
return true;
case R.id.menu_logout:
dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(
MainActivity.this, R.style.Theme_AppCompat_Light_Dialog));
dialogBuilder
.setTitle(getResources().getString(R.string.logoutAlertTitle))
.setIcon(R.drawable.ic_logout).setMessage(getResources().getString(R.string.logoutAlertMessage)).setPositiveButton(getResources().getString(R.string.logoutAlertYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
((RelativeLayout) findViewById(R.id.fl_mainContent))
.animate()
.alpha(0f)
.setListener(
new AnimatorListenerAdapter() {
public void onAnimationEnd(
Animator animation) {
mDrawerLayout
.setVisibility(View.INVISIBLE);
mDrawerLayout
.setAlpha(1f);
mDrawerLayout
.animate()
.setListener(null);
}
});
userFunctions.logoutUser(getApplicationContext());
Intent i = new Intent(MainActivity.this, LoginActivity.class);
// MainActivity.this.deleteDatabase("cobytu_db");
startActivity(i);
finish();
}
})
.setNegativeButton(getResources().getString(R.string.logoutAlertNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.show();
return true;
}
return false;
}
public int filterCounter = 0;
class FetchCountTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// example count. This is where you'd
// query your data store for the actual count.
return 5;
}
#Override
public void onPostExecute(Integer count) {
setNotifCount(count);
}
}
private void setNotifCount(int count){
filterCounter = count;
supportInvalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
MenuItem item = menu.findItem(R.id.action_filter);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Log.d("mTag", "onCreateOptionsMenu: this: " + this.toString());
UsefulFunctions.setBadgeCount(this, icon, filterCounter);
return true;
}
#Override
public void onRefreshFilters(int counter) {
setupTablayout();
Toast.makeText(MainActivity.this, "List has been refreshed! " + counter, Toast.LENGTH_SHORT).show();
filterCounter = counter;
new FetchCountTask.execute();
}
}

Categories

Resources