How to add Toolbar to PreferenceActivity - java

I am creating an app which have a setting PreferenceActivity with actionbar and that's working fine. I want to use another custom PreferenceActivity with actionbar which is using a layout (activity_about.xml) and preference layout (about_preferences.xml). But when i run the app it's causing my app to crash on calling that activity. Probably the actionbar is returning the Null, i can't figure it out where is the problem. Please help.
My ActivityAbout.java
public class ActivityAbout extends PreferenceActivity {
private AppCompatDelegate mDelegate;
private ActionBar actionBar;
private SharedPref sharedPref;
private View parent_view;
private TextView ver;
Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.about_preferences);
setContentView(R.layout.activity_about);
View lv = findViewById(android.R.id.list);
if (lv != null) lv.setPadding(0, 0, 0, 0);
final Preference prefPrivacy = (Preference) findPreference(getString(R.string.pref_title_privacy));
final Preference prefTerm = (Preference) findPreference(getString(R.string.pref_title_term));
final Preference prefBuild = (Preference) findPreference(getString(R.string.pref_title_build));
final Preference prefCopyright = (Preference) findPreference(getString(R.string.pref_title_copyright));
String versionName = BuildConfig.VERSION_NAME;
ver = (TextView) findViewById(R.id.version);
ver.setText("Version "+versionName);
prefBuild.setSummary("Version "+versionName);
int y = Calendar.getInstance().get(Calendar.YEAR);
prefCopyright.setSummary("Copyright © "+y+" Get Rid Remedy.\nAll Right Reserved.");
prefPrivacy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogPrivacy(ActivityAbout.this);
return false;
}
});
prefTerm.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogTerm(ActivityAbout.this);
return false;
}
});
initToolbar();
}
public void dialogPrivacy(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_privacy));
builder.setMessage(activity.getString(R.string.content_privacy));
builder.setPositiveButton("OK", null);
builder.show();
}
public void dialogTerm(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_term));
builder.setMessage(activity.getString(R.string.content_term));
builder.setPositiveButton("OK", null);
builder.show();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
private void initToolbar() {
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
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;
}
}
Here is the about_preferences layout.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="#string/pref_title_dev_email"
android:summary="#string/developer_email"
android:title="#string/pref_title_dev_email"/>
<Preference
android:key="#string/pref_title_copyright"
android:summary="#string/copyright"
android:title="#string/pref_title_copyright"/>
<Preference
android:key="#string/pref_title_build"
android:summary="#string/app_version"
android:title="#string/pref_title_build"/>
<Preference
android:key="#string/pref_title_privacy"
android:title="#string/pref_title_privacy"
android:widgetLayout="#layout/ic_about"/>
<Preference
android:key="#string/pref_title_term"
android:title="#string/pref_title_term"
android:widgetLayout="#layout/ic_about"/>
Here is activity_about.
<?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:id="#+id/activity_about"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overridecode.getridremedy.ActivityAbout">
<android.support.design.widget.AppBarLayout
android:id="#+id/tool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_below="#+id/tool"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
app:srcCompat="#mipmap/ic_launcher"
android:id="#+id/imageView" />
<TextView
android:text="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="#73000000"
android:id="#+id/app_title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/version" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
The error i am getting:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.overridecode.getridremedy/
com.overridecode.getridremedy.ActivityAbout}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

Add an ID to your Toolbar:
<include
android:id="#+id/toolbar_prefs"
layout="#layout/toolbar" />
And call setSupportActionBar() (passing your Toolbar instance) before calling getSupportActionBar():
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_prefs);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
Otherwise getSupportActionBar() will return null.

As per my experience, I found there is no ActionBar in preference activity. So,
There are following steps to add toolbar in your activity
Add in xml
<include layout="#layout/toolbar" />
Set Toolbar in java class using following code.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarId);
setSupportActionBar(toolbar);
NOTE: here you need to use this code in starting of intitToolbar() method.
Import proper class/package for your toolbar. From your comments seems you need to import
import android.support.v7.widget.Toolbar;
Hope this may help you. If helps, please approve it as right answer.

Related

Android BottomNavigationView not shows

I want to implement BottomNavigationView in my Android app but my code does not displays this BottomNavigationView. Here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
private final FragmentHome fragmentHome = new FragmentHome();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnItemSelectedListener(item -> {
showFragment(item.getItemId());
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragmentHome);
bottomNavView.setSelectedItemId(R.id.action_home);
ft.commit();
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.action_home:
if (bottomNavView.getSelectedItemId() != R.id.action_home) {
fragment = fragmentHome;
newPosition = 0;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_action_bar, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View arg0) {
setItemsVisibility(menu, searchItem, false);
}
#Override
public void onViewDetachedFromWindow(View arg0) {
setItemsVisibility(menu, searchItem, true);
}
});
return super.onCreateOptionsMenu(menu);
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
main_activity.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="#menu/menu_bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
menu_bottom_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_home"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/home" />
<item
android:id="#+id/action_words_ranking"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/words_ranking" />
<item
android:id="#+id/action_users_ranking"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/users_ranking" />
<item
android:id="#+id/action_messages"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/messages" />
<item
android:id="#+id/action_notifications"
android:icon="#drawable/ic_launcher_foreground"
android:title="#string/notifications" />
</menu>
Not only this BottomNavigationView not displays it even not occupies any vertical space.
Help me please!
EDIT
I also simplified my day/night themes but no effect.
EDIT 2
I know where! There is a problem with ft.replace(R.id.content_frame, fragmentHome); in onCreate. It shows things from fragment but skip BottomNavView from MainActivity But how to solve that?
FragmentHome.java
public class FragmentHome extends Fragment {
private MyViewModel loginViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initBinding();
loginViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String string) {
Toast.makeText(requireActivity(), "cześć " + string, Toast.LENGTH_SHORT).show();
}
});
}
private void initBinding() {
FragmentHomeBinding binding = DataBindingUtil.setContentView((requireActivity()), R.layout.fragment_home);
loginViewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setMyViewModel(loginViewModel);
binding.setLifecycleOwner(this);
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="myViewModel"
type="pl.jawegiel.abc.viewmodel.MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="#{ ()-> myViewModel.setText() }"/>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#={myViewModel.text}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Does it return any errors? There is no problem in your code. Could you check the log?
Add app:layout_constraintBottom_toTopOf="#id/bottom_navigation" line to FrameLayout and change it layout_height attribute to 0dp. You must specify limit for FrameLayout, otherwise it can overlay BottomNavigationBar
try to add
layout_constraintTop_toBottomOf="#+id/content_frame"
SOLVED. The problem was with DataBinding in fragment. I needed to move initBinding() and return binding.getRoot() in onCreateView().

Android NullPointerException Toolbar.setNavigationOnClickListener null object reference

Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}

Items in different activities not collapsing

I am trying to create a preferences activity but for some reason, my Switch control is not behaving the way that it is supposed to. It prevents the desired itms from collapsing + my app crashes whenever I navigate to the SettingsActivity. I really don't understand why this is happening when the component has clearly been declared. Below is my code (the code for pages 2 and 3 have been omitted to reduce clutter within my question):
activity_page1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_page1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.apptacularapps.settingsapp.Page1Activity">
<View
android:id="#+id/blue_square"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:background="#drawable/shape_blue_square" />
<View
android:id="#+id/blue_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_blue_circle"
android:layout_marginBottom="20dp"
android:layout_below="#id/blue_square"/>
<View
android:id="#+id/blue_rectangle"
android:layout_width="300dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_blue_rectangle"
android:layout_below="#id/blue_circle"/>
</RelativeLayout>
Page1Activity.java
public class Page1Activity extends AppCompatActivity {
boolean squareState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings() {
if (squareState) {
findViewById(R.id.blue_square).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.blue_square).setVisibility(View.GONE);
}
}
}
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.packagename.settingsapp.SettingsActivity">
<android.support.v7.widget.SwitchCompat
android:id="#+id/square_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show squares"
style="#android:style/TextAppearance.Large" />
<android.support.v7.widget.SwitchCompat
android:id="#+id/circle_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show circles"
style="#android:style/TextAppearance.Large"
android:layout_below="#id/square_switch"/>
<android.support.v7.widget.SwitchCompat
android:id="#+id/rectangle_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show rectangles"
style="#android:style/TextAppearance.Large"
android:layout_below="#id/circle_switch"/>
</RelativeLayout>
SettingsActivity.java
public class SettingsActivity extends AppCompatActivity {
boolean squareState;
SwitchCompat squareSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings(){
squareSwitch.setChecked(squareState);
}
#Override
public void onPause(){
super.onPause();
savePreferences();
}
private void savePreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("square_state", squareState);
editor.apply();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
switch(id){
case R.id.square_switch:
squareState = isChecked;
break;
}
}
}
 
Current result
Expected result
You're not attaching squareSwitch to any UI component. Update your SettingsActivity.java to the following:
public class SettingsActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
boolean squareState;
SwitchCompat squareSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
squareSwitch = (SwitchCompat)findViewById(R.id.square_switch); //add this line
squareSwitch.setOnCheckedChangeListener(this); //Also add this
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings(){
squareSwitch.setChecked(squareState);
}
#Override
public void onPause(){
super.onPause();
savePreferences();
}
private void savePreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("square_state", squareState);
editor.apply();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
switch(id){
case R.id.square_switch:
squareState = isChecked;
break;
}
}
Also, you don't need to implement CompoundButton.OnCheckedChangeListener and override onCheckedChanged in Page1Activity you might want to remove those from there.

How to hide toolbar fully under status bar when scrolling recyclerview

I try to make scrolling behavior for toolbar as embodied in Google Photo. But my toolbar not hiding fully under status bar.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:clipChildren="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
Check out this library Android-ObservableScrollView
Whatsapp uses the same one
I am using this code to hide Tool bar,you can take help from code write below.
public class MainActivity extends AppCompatActivity implements ObservableScrollViewCallbacks{
#Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
ActionBar ab = getSupportActionBar();
if (scrollState == ScrollState.UP) {
if (ab.isShowing()) {
ab.hide();
// image.setVisibility(View.GONE);
}
} else if (scrollState == ScrollState.DOWN) {
if (!ab.isShowing()) {
ab.show();
// image.setVisibility(View.VISIBLE);
}
}
}
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// image = (ImageView) findViewById(R.id.image);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ObservableListView listView = (ObservableListView) findViewById(R.id.list);
listView.setScrollViewCallbacks(MainActivity.this);
ArrayList<String> items = new ArrayList<String>();
for (int i = 1; i <= 100; i++) {
items.add("Item " + i);
}
listView.setAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, items));
}
}

Adding PreferenceScreen to linearlayout

Hi I am new to Android and Java and have run into a problem. My problem is that i am trying to add a PreferenceScreen to my linear layout so I am able to set an setOnSeekBarChangeListener() on the seekbar in res/layout/activity_main.xml. At the moment the PreferenceScreen and the LinearLayout get added to the view but they are on top of each other which is not what I want. Instead I want the PreferenceScreen to go in place of the ListView inside my layout file.
res/xml/settings.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Category"
android:key="category_preference">
<SwitchPreference
android:key="switch_preference"
android:title="Title"
android:summary="Summary"
android:defaultValue="true" />
<CheckBoxPreference
android:key="checkbox_preference"
android:title="Title"
android:summary="Summary"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<SeekBar
android:id="#+id/main_seek_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
setContentView(R.layout.activity_main);
SeekBar seekBar = (SeekBar) findViewById(R.id.main_seek_bar);
seekBar.setOnTouchListener(new SeekBar.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
});
}
public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
onSharedPreferenceChanged(null, "");
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("switch_preference")) {
Toast.makeText(getActivity(), "Switch", Toast.LENGTH_LONG).show();
}
}
}
}
in your res/layout/activity_main.xml file change
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
to
<fragment android:id="#+id/fragment_settings"
android:layout_width="fill_parent"
android:name="yourpackagename.MainActivity$SettingsFragment"
android:layout_height="fill_parent" />
and then in your MainActivity.java file remove the following line
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();

Categories

Resources