My app basicly contains two activities, a main-activity and a settings-activity.
Settings-activity is launched by
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
, which contains some fragments. I use the up navigation, which works perfectly in settings-activity between the fragments, but however I don't return to my main-activity when pressing the back button. The setDisplayHomeAsUpEnabled command is in my settings-activity, bc it didn't helped to solve my problem when I positioned it in my main-activity.
In my manifest I've declared main-activity as the parent activity for settings-activity.
So what do I have to do? - lot's of thanks!
My Mainactivity
package user.example;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
My SettingsActivity: (I've left out the fragments, but the same error is reproduced)
package user.example;
import android.support.v7.app.ActionBar;
public class SettingsActivity extends AppCompatPreferenceActivity {
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
AppCompatPreferenceActivity: (started by Settings.activity)
package user.example;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
I figured out that I had to put this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
into my AppCompatPreferenceActivity.java, now everything wokrs, thanks for all help so far!!! :)
I think you need to set the "main Activity" as the Parent Activity to "Settings Activity" in the Mainfest like that
<activity android:name=".SettingActivity"
android:parentActivityName=".MainActivity"></activity>
Edit
You neeed to add in the Setting Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Related
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below
enter image description here
Here is explore activity code
package com.example.windows81.travelspoc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class ExploreActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.menu_second, menu); <- remove this
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
Here is my homeactivity code
package com.example.windows81.travelspoc;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.Timer;
import java.util.TimerTask;
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout.addDrawerListener(mtoggle);
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8,0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mtoggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.explore:
// do what you want here
myMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class MyTimerTask extends TimerTask{
#Override
public void run() {
HomeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
}else if (viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
}else{
viewPager.setCurrentItem(0);
}
}
});
}
}
public void myMethod(){
Intent intent = new Intent(this,ExploreActivity.class);
startActivity(intent);
}
public void exploreActivity(View view){
myMethod();
}
public void packagesActivity(View view){
Intent intent = new Intent(this,PackagesActivity.class);
startActivity(intent);
}
public void dealsActivity(View view){
Intent intent = new Intent(this,DealsActivity.class);
startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.explore) {
myMethod();
}
return false;
}
}
Here is my Base activity code
package com.example.windows81.travelspoc;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
/**
* Created by Windows 8.1 on 11/15/2017.
*/
public class BaseActivity extends AppCompatActivity{
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.explore:
myMethod();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void myMethod(){
Intent intent = new Intent(this,ExploreActivity.class);
startActivity(intent);
}
public void exploreActivity(View view){
myMethod();
}
public void packagesActivity(View view){
Intent intent = new Intent(this,PackagesActivity.class);
startActivity(intent);
}
public void dealsActivity(View view){
Intent intent = new Intent(this,DealsActivity.class);
startActivity(intent);
}
}
Create a base activity in which u write code for menu items then extend the base activity to all your inner activities.
For Title
Create a common title layout.
Then in your HomeActivity
abstract class HomeActivity extends Activity {
protected TextView txtHeading;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setHeading(int resId) {
if(tv_title == null)
txtHeading = findViewById(R.id.tv_title);
if(tv_title != null)
txtHeading.setText(resId);
}
}
Then in other activities like activity_main.xml
MainActivity
class MainActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setHeading(R.string.heading_main);
}
}
same goes for other activities
For Same Menu Option
public class HomeActivity extends Activity {
// other overidden methods
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item:
// do what you want here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Then in child activity
public class ChildActivity extends BaseActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.menu_second, menu); <- remove this
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
If you have same menu through out all activities then i will advice you to create one
BaseActivity then extends it to AppcompatActivity
Make Activity1 -> extends BaseActivity
Magic comes here -> You don't have to use setContentView for all the time.
Make BaseActivity with One XML -> FrameLayout -> with Your
ToolBar & FrameLayout
Now in the Activity1 inflate your view in FrameLayout of BaseActivity
And follow the same system for all the activities.
I had the same situation -> I had to display sideMenu in every Activity so i ended up with this solution.
HomeActivity.java (Navigational Activity)
import android.app.Fragment;
import android.app.FragmentManager;
mport android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.Fragments.BrowseAdFragment;
import com.example.dellpc.reuz_app.Fragments.LoginFragment;
import com.example.dellpc.reuz_app.Fragments.NetworkErrorFragment;
import com.example.dellpc.reuz_app.Fragments.TopMainFragment;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.utils.CheckNetworkConnection;
import com.example.dellpc.reuz_app.utils.NetworkErrorFragmentSetter;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Fragment fragment;
private String title;
private DrawerLayout drawer;
private NavigationView navigationView;
private View layout;
private User user=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("REUZ");
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
System.out.println(getSupportActionBar().getHeight());
View headerLayout = navigationView.getHeaderView(0);
layout=headerLayout.findViewById(R.id.navigationHeader);
getSupportActionBar().setTitle("REUZ");
this.setInitialFragment();
this.listeners();
/*this.getUserObject();*/
}
public void listeners(){
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(CheckNetworkConnection.isConnectionAvailable(HomeActivity.this))
{
getLoginFragment();
}
else{
fragment= NetworkErrorFragmentSetter.getNetworkErrorFragment(HomeActivity.this);
replaceFragment();
}
}
});
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
if (currentFragment instanceof TopMainFragment) {
getSupportActionBar().setTitle("REUZ");
}
else if (currentFragment instanceof BrowseAdFragment) {
getSupportActionBar().setTitle("All Categories");
}
else if (currentFragment instanceof LoginFragment) {
getSupportActionBar().setTitle("LOGIN");
}
else if(currentFragment instanceof NetworkErrorFragment){
getSupportActionBar().setTitle("NETWORK ERROR");
}
}
});
}
#Override
public void onBackPressed() {
//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.home, 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_home) {
// Handle the home action
setInitialFragment();
} else if (id == R.id.nav_browse) {
fragment=new BrowseAdFragment();
} else if (id == R.id.nav_submitAd) {
Intent intent=new Intent(getApplicationContext(),SubmitAdActivity.class);
startActivity(intent);
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_my_ads) {
} else if (id == R.id.nav_wishList) {
}
replaceFragment();
//drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setTitleOnActionBar(String title) {
getSupportActionBar().setTitle(title);
}
public void setInitialFragment(){
fragment=new TopMainFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
// ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void getLoginFragment(){
fragment=new LoginFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void replaceFragment(){
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onResume() {
super.onResume();
// Set the title
}
public void getUserObject(User user){
this.user=user;
if(user!=null){
changeLayoutName();
}
}
public void changeLayoutName(){
TextView name= (TextView)layout.findViewById(R.id.textView8);
name.setText(user.getName());
}
}
LoginFragment.java(Fragment)
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.dellpc.reuz_app.Activities.HomeActivity;
import com.example.dellpc.reuz_app.Activities.RegisterActivity;
import com.example.dellpc.reuz_app.Activities.UnableToLoginActivity;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.Validator.IValidation;
import com.example.dellpc.reuz_app.Validator.Validation;
import com.example.dellpc.reuz_app.dao.IUserDAO;
import com.example.dellpc.reuz_app.dao.UserDAO;
public class LoginFragment extends Fragment {
private EditText emailET, passwordET;
private Button loginBTN;
private TextView utlTV, registerTV, invalidEmailTV, invalidPasswordTV;
private View view;
private NavigationView navigationView;
private User user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_login, container, false);
Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);
((HomeActivity)getActivity()).getSupportActionBar().setTitle("LOGIN");
this.mapping();
this.listeners(view);
return view;
}
public void mapping(){
emailET = (EditText)view.findViewById(R.id.emailET);
passwordET = (EditText)view.findViewById(R.id.passwordET);
loginBTN = (Button)view.findViewById(R.id.loginBTN);
utlTV = (TextView)view.findViewById(R.id.utlTV);
invalidEmailTV = (TextView)view.findViewById(R.id.invalidEmailTV);
invalidPasswordTV = (TextView)view.findViewById(R.id.invalidPasswordTV);
registerTV = (TextView)view.findViewById(R.id.registerTV);
}
public void listeners(View view){
loginBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
validateAndMoveToActivity(email, password);
}
});
utlTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent utlIntent = new Intent(getActivity(), UnableToLoginActivity.class);
startActivity(utlIntent);
}
});
registerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(getActivity(), RegisterActivity.class);
startActivity(registerIntent);
}
});
emailET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
passwordET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s)
{
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
}
public void validateAndMoveToActivity(String email, String password){
IValidation iValidation = new Validation();
if(!iValidation.isFilled(email) && iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
}
else if(iValidation.isFilled(email) && !iValidation.isFilled(password)) {
invalidPasswordTV.setText("This field is required");
}
else if(!iValidation.isFilled(email) && !iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
invalidPasswordTV.setText("This field is required");
}
else
{
IUserDAO iUserDAO = new UserDAO(getActivity().getApplicationContext());
/*
if(iUserDAO.isEmailPasswordExist(email, password))*/
if(iUserDAO.isEmailExist(email)){
user=iUserDAO.isEmailPasswordExist(email,password);
if(user!=null)
{
Toast.makeText(view.getContext(), "Successful Login", Toast.LENGTH_SHORT).show();
HomeActivity home=new HomeActivity();
home.getUserObject(user);
/* Intent homeACIntent = new Intent(view.getContext(), HomeActivity.class);
homeACIntent.putExtra("user",user);
startActivity(homeACIntent);*/
// Remove this fragment.
getActivity().getFragmentManager().popBackStack();
}
else {
invalidPasswordTV.setText("Invalid email or password");
}
}
else {
// After successful login where do you want to move your activity.
invalidEmailTV.setText("Invalid phone number or email");
}
}
}
#Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putSerializable("user",user);
}
}
HomeActivity contains Two Fragments- Login And Top
Initially it shows top fragment
Login Fragment has a option for registration
After successful registration the user is navigated to login fragment
Now after Login the control must reach to the "Top" and the name of the user has to written in the Navigation Drawer
How to do it?
this is my Drawer .t want to write name of User instead of welcome to Reuz
HomeActivity
I see that you're saving the user details in your local database, and then trying to load the data after the user has successfully logged in. The issue that you're facing is that the TextView is not being updated. One possible solution that you can call the changeLayoutName() method from the onViewCreated() method of the TopMainFragment itself.
I am making an application in Android for use with Cardboard.
At the moment I have implemented a menu that extends Activity in MainActivity and a code that activates the camera for a Cardboard (extending from CardboardActivity). My problem is when the menu selected the option in which launched this code. How I can throw a CardboardActivity within an Activity?
Sorry for my English. :(
This is the code:
package com.example.dbg.CamaraCV;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.vrtoolkit.cardboard.CardboardActivity;
public class MainActivity extends AppCompatActivity {
private Toolbar appbar;
private DrawerLayout drawerLayout;
private NavigationView navView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.dbg.CamaraCV.R.layout.activity_main);
appbar = (Toolbar)findViewById(com.example.dbg.CamaraCV.R.id.appbar);
setSupportActionBar(appbar);
getSupportActionBar().setHomeAsUpIndicator(com.example.dbg.CamaraCV.R.drawable.ic_nav_menu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout)findViewById(com.example.dbg.CamaraCV.R.id.drawer_layout);
/*
//Eventos del Drawer Layout
drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
*/
navView = (NavigationView)findViewById(com.example.dbg.CamaraCV.R.id.navview);
navView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
boolean fragmentTransaction = false;
Fragment fragment = null;
CardboardActivity CardboardActivity =null;
switch (menuItem.getItemId()) {
case com.example.dbg.CamaraCV.R.id.menu_seccion_0:
fragment = new Fragment0();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_1:
startActivity(new Intent(MainActivity.this, CamaraCardBoard.class));
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_2:
fragment = new Fragment2();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_3:
fragment = new Fragment3();
fragmentTransaction = true;
break;
}
if(fragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(com.example.dbg.CamaraCV.R.id.content_frame, fragment)
.commit();
menuItem.setChecked(true);
getSupportActionBar().setTitle(menuItem.getTitle());
}
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(com.example.dbg.CamaraCV.R.menu.menu_navview, 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.
switch(item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
Im trying to use drawer toggle in an action bar with sherlock. This is my main activity:
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshAttacher;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.mejorandroid.ejemplo3_clase3.fragments.MainFragment;
import com.mejorandroid.ejemplo3_clase3.fragments.TermsFragment;
public class MainActivity extends SherlockFragmentActivity
implements OnItemClickListener{
private ListView drawer_list;
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle drawer_toggle;
private PullToRefreshAttacher pullToRefreshAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pullToRefreshAttacher = PullToRefreshAttacher.get(this);
drawer_list = (ListView) findViewById(R.id.left_drawer);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
ArrayAdapter<String> drawer_adapter = new ArrayAdapter<String>(this,
R.layout.drawer_list_item, getResources().getStringArray(
R.array.array_drawer_options));
drawer_list.setAdapter(drawer_adapter);
drawer_list.setOnItemClickListener(this);
selectItem(0);
drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
};
drawer_layout.setDrawerListener(drawer_toggle);
getSherlock().getActionBar().setDisplayHomeAsUpEnabled(true);
getSherlock().getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawer_toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawer_toggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public PullToRefreshAttacher getAttacher() {
return pullToRefreshAttacher;
}
public void selectItem(int position){
Fragment f;
if(position==0){
f = new MainFragment();
}else{
f = new TermsFragment();
}
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.main_content, f)
.commit();
drawer_list.setItemChecked(position, true);
setTitle(drawer_list.getItemAtPosition(position).toString());
drawer_layout.closeDrawer(drawer_list);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
selectItem(position);
}
}
In the method onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
I get:
How can I fix this??
This is my main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
I had the same problem and this works for me:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (drawer_layout.isDrawerOpen(drawer_list)) {
drawer_layout.closeDrawer(drawer_list);
} else {
drawer_layout.openDrawer(drawer_list);
}
}
return super.onOptionsItemSelected(item);
}
I don't know if this problem is already fixed in the newest release of the Sherlock library / support library, but the workaround does a good job.
I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}