This is my MainActivity
public class ProjectDetailsActivity extends AppCompatActivity {
private static final String TAG = ProjectDetailsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
if (savedInstanceState == null) {
addFragment(new ProjectDetailsFragment(), false);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_detail);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Button Clicked", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void addFragment(Fragment f, boolean isAddToBack) {
FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container, f);
if (isAddToBack) {
mFragmentTransaction.addToBackStack(null);
}
mFragmentTransaction.commit();
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
This my xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.abcd.scrollappdemo.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/toolbar_scrollable_image_height"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/title_bg" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|start"
android:text="Garden Residency II"
android:textColor="#ffffffff" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_detail"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/include_layout"
layout="#layout/project_detail_content" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
This is my fragment class`
public class ProjectDetailsFragment extends BaseFragment implements View.OnClickListener {
private static final String TAG = ProjectDetailsFragment.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.fragment_details, container, false);
mappingWidgets(mView);
return mView;
}
private void mappingWidgets(View v) {
}
#Override
public void onClick(View v) {
}
}
Error Log :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setNavigationIcon(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setNavigationIcon(int)' on a null object reference
at com.abc.xyz.abcActivity.onCreate(ProjectDetailsActivity.java:32)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Activity theme in Mainfest is -
#style/Apptheme.Noactionbar
Just by putting these code in fragment I am able to access the actionbar from fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.activity_detail, container, false);
final Toolbar toolbar = (Toolbar) mView.findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.setTitle("Project Details");
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout)mView.findViewById(R.id.collapsing_toolbar);
Related
I want to have the following screen:
When I click IMAGE 1 and IMAGE 2 buttons I want in IMAGE ZONE to appear Image1.jpg and Image2.jpg respectively. I want Image1.jpg and Image2.jpg to be in different fragments and replace those fragments on button click rather than changing simply the android:src of the ImageView in IMAGE ZONE on button click. I want Image1.jpg to be the first image to appear when opening the activity. I can't find how to do that with fragments in Xamarin.Android
You can create two Fragment and its xml first.
FragmentOne :
public class Fragment1 : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
return inflater.Inflate(Resource.Layout.layoutFragment1, container, false);
//return base.OnCreateView(inflater, container, savedInstanceState);
}
}
and its xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/th2"/>
</LinearLayout>
FragementTwo :
public class Fragment2 : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
return inflater.Inflate(Resource.Layout.layoutFragment2, container, false);
//return base.OnCreateView(inflater, container, savedInstanceState);
}
}
and its xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/th2"/>
</LinearLayout>
Then in MainActivity , you can set its xml as follow :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="80dip"
android:orientation="horizontal">
<Button
android:id="#+id/buttonone"
android:layout_width="150dip"
android:layout_height="80dip"
android:text="FragmentOne"/>
<Button
android:id="#+id/buttontwo"
android:layout_width="150dip"
android:layout_height="80dip"
android:text="FragmentTwo"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/containerView"
android:layout_width="match_parent"
android:layout_height="430dip">
</RelativeLayout>
</LinearLayout>
Finally , in MainActivity.cs implement this function :
public class MainActivity : AppCompatActivity
{
Android.Support.V4.App.Fragment fragmentOne;
Android.Support.V4.App.Fragment fragmentTwo;
Android.Support.V4.App.FragmentTransaction fragmentManager;
[Obsolete]
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button buttonone = FindViewById<Button>(Resource.Id.buttonone);
buttonone.Click += Buttonone_Click;
Button buttontwo = FindViewById<Button>(Resource.Id.buttontwo);
buttontwo.Click += Buttontwo_Click;
fragmentOne = new Fragment1();
fragmentTwo = new Fragment2();
fragmentManager = SupportFragmentManager.BeginTransaction();
fragmentManager.Add(Resource.Id.containerView, fragmentOne);
//adding first fragment when entering activity
fragmentManager.Commit();
}
private void Buttonone_Click(object sender, System.EventArgs e)
{
//throw new System.NotImplementedException();
Console.WriteLine("Buttonone_Click");
fragmentManager = SupportFragmentManager.BeginTransaction();
// replace to be the first fragment
fragmentManager.Replace(Resource.Id.containerView, fragmentOne);
fragmentManager.Commit();
}
private void Buttontwo_Click(object sender, System.EventArgs e)
{
//throw new System.NotImplementedException();
Console.WriteLine("Buttontwo_Click");
fragmentManager = SupportFragmentManager.BeginTransaction();
// replace ro be the second fragment
fragmentManager.Replace(Resource.Id.containerView, fragmentTwo);
fragmentManager.Commit();
}
}
The effect as follow :
I am trying to implement a simple navigation using Navigation Component with navigation graph and navigation controller.
I have my MainActivity with actionbar with hamburger icon and app title, a drawer navigation and content area.
Content area is where I display different fragments.
Content area is first loaded with my homescreenFragment containing 4 buttons (news, events, timetable, profile) - each of them loads fragment into my MainActivity's Content area.
It works fine, the only problem is the following:
When I press news button and navigate from my homescreen to my NewsFragment it loads fragment OK and changes actionbar title to News. Hamburger icon is changed to 'Up button' icon, but when I press on it, application opens Navigation Drawer as if I press on the hamburger icon instead of navigating me back to the home screen.
How do I make Up button to go up and not showing left navigation drawer ?
here is my MainActivity.java:
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 androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
public class MainActivity extends AppCompatActivity {
Toolbar m_toolbar;
DrawerLayout m_drawer;
ActionBarDrawerToggle m_toggle;
NavigationView m_navigationView;
NavController m_navController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_toolbar = findViewById(R.id.toolbar);
setSupportActionBar(m_toolbar);
m_drawer = findViewById(R.id.drawer_layout);
m_navigationView = findViewById(R.id.nav_drawer_view);
m_navController = Navigation.findNavController(this, R.id.content);
m_toggle = new ActionBarDrawerToggle(
this, m_drawer, m_toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
m_drawer.addDrawerListener(m_toggle);
//m_toggle.syncState();
//connect actionbar icon and drawer with nav controller
NavigationUI.setupWithNavController(m_navigationView, m_navController);
NavigationUI.setupActionBarWithNavController(this, m_navController);
NavigationUI.setupActionBarWithNavController(this, m_navController, m_drawer);
}
#Override
public boolean onSupportNavigateUp() {
return Navigation.findNavController(this, R.id.nav_drawer_view).navigateUp() || super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
my activity_main.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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="#navigation/nav_graph"
app:defaultNavHost="true"/>
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
navigation graph:
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/nav_graph"
app:startDestination="#id/homeScreenFragment">
<fragment
android:id="#+id/homeScreenFragment"
android:name="com.mysample.meganews.Fragments.HomeScreenFragment"
android:label="#string/app_name"
tools:layout="#layout/home_screen_fragment" >
<action
android:id="#+id/action_to_news"
app:destination="#id/newsFragment"
app:enterAnim="#anim/nav_default_enter_anim"
app:exitAnim="#anim/nav_default_exit_anim" />
<action
android:id="#+id/action_to_events"
app:destination="#id/eventsFragment"
app:enterAnim="#anim/nav_default_pop_enter_anim"
app:exitAnim="#anim/nav_default_pop_exit_anim" />
</fragment>
<fragment
android:id="#+id/newsFragment"
android:name="com.mysample.meganews.Fragments.NewsFragment"
android:label="#string/hs_title_news"
tools:layout="#layout/news_fragment" />
<fragment
android:id="#+id/eventsFragment"
android:name="com.mysample.meganews.Fragments.EventsFragment"
android:label="events_fragment"
tools:layout="#layout/events_fragment" />
</navigation>
HomeScreenFragment.java file:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeScreenFragment extends Fragment {
public HomeScreenFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.home_screen_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RelativeLayout rl_news = view.findViewById(R.id.ll_news_btn);
RelativeLayout rl_events = view.findViewById(R.id.ll_events_btn);
rl_news.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_to_news));
rl_events.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_to_events));
}
}
build.gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.mysample.meganews"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'android.arch.lifecycle:extensions:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha11'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha11'
}
This problem was due to mixing of different APIs . Here is the right code:
activity_main.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark" />
<fragment
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="#navigation/nav_graph"
app:defaultNavHost="true"/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
MainActivity.java:
import android.os.Bundle;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.view.MenuItem;
import android.view.ViewParent;
public class MainActivity extends AppCompatActivity
{
private Toolbar mToolbar;
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mToggle;
private NavigationView mNavigationView;
private NavController mNavController;
private MainViewModel mViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
setupNavigation();
}
private void setupNavigation()
{
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawer = findViewById(R.id.drawerLayout);
mNavigationView = findViewById(R.id.nav_drawer_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// // we need this line to handle the navigation
// boolean handled = NavigationUI.onNavDestinationSelected(menuItem, mNavController);
// if (handled) {
// ViewParent parent = mNavigationView.getParent();
// if (parent instanceof DrawerLayout) {
// ((DrawerLayout) parent).closeDrawer(mNavigationView);
// }
// }
return true;
}
});
mNavController = Navigation.findNavController(this, R.id.content);
NavigationUI.setupActionBarWithNavController(this, mNavController, mDrawer);
// Tie nav graph to items in nav drawer
NavigationUI.setupWithNavController(mNavigationView, mNavController);
}
#Override
public boolean onSupportNavigateUp() {
//return Navigation.findNavController(this, R.id.content).navigateUp();
//return mNavController.navigateUp() || super.onSupportNavigateUp();
return NavigationUI.navigateUp(mNavController, mDrawer);
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.START)) {
mDrawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
I had the same issue and fixed it with below workaround.
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller,
#NonNull NavDestination destination, #Nullable Bundle arguments) {
if (mAppBarConfiguration.getTopLevelDestinations().contains(destination.getId())) {
mToggle.setDrawerIndicatorEnabled(true);
} else {
mToggle.setDrawerIndicatorEnabled(false);
}
}
});
Also make sure to set the click listener to ActionBarDrawerToggle as below.
mToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.onBackPressed();
}
});
Navigation handle this by default you do not have to explicitly handle listener for this.
In your activity override "onSupportNavigationUp"
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController, drawer_layout)
}
and do above. It will handle back button and hamburger icon by default.
i'm new on Android. I'm trying to implent an actionbar im my activity. Everytime i run that, the app crash.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_percorsodisabili);
//Option Bar
getSupportActionBar().setTitle("Percorso Bici");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Resources res = getResources();
myVist3 = (ListView) findViewById(R.id.myVist3);
items = res.getStringArray(R.array.nomi_percorsi3);
descriptions = res.getStringArray(R.array.desc_percorsi3);
content = res.getStringArray(R.array.desc_percorsi3);
ItemAdapter itemAdapter = new ItemAdapter(percorsodisabili.this, items,foto,descriptions,content);
myVist3.setAdapter(itemAdapter);
}
}
Add the toolbar to your activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="56dp" />
<RelativeLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar">
<!--YOUR LAYOUT CODE-->
</RelativeLayout>
Then initialize java code for activity:
Use android.support.v7.widget.Toolbar in case you are using AppCompactActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
I have two activities namely mainactivity and main2activity. Mainactivity has three buttons and main2activity has list view.
When I click button string is passed to main2activity and is displayed in main2activity.
So now I want also image in listview. corresponding image for button selected. Below are my codes.
MainActivity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button addButton;
String text1 ="Item 1";
String text2 ="Item 2";
String text3 ="Item 3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text1);
startActivity(intent);
}
});
Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text2);
startActivity(intent);
}
});
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text3);
startActivity(intent);
}
});
}
Main2activity
public class Main2Activity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
#Override
protected void onRestart() {
super.onRestart();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Global.list1);
listView.setAdapter(adapter);
if (Global.list1.size() < 1) {
Global.list1 = new ArrayList<>();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent1 = getIntent();
listView = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Global.list1);
listView.setAdapter(adapter);
String havestring = intent1.getStringExtra("text");
if (havestring != null) {
Global.list1.add(havestring);
adapter.notifyDataSetChanged();
}
Button backbtn = (Button) findViewById(R.id.backbtn);
backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageview"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
</LinearLayout>
So how to set custom adapter that will add corresponding image with string added.
Can it be done using if else statement in custom adapter???
Please do help me
for same.
Can anyone help me out???
I want to display spinner in action bar(not in activity,in Fragment).for that i did below things
Step-1 (spinnermenu.xml)
`<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menuSort"
android:showAsAction="ifRoom"
android:actionLayout="#layout/spinner"/>
</menu>`
Step-2 (spinner.xml)
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="70dp"
android:layout_height="wrap_content" />
step-3 (Code)
public class All extends Fragment{
ArrayList<String> spinnerlist;
ArrayAdapter<String> spinneradapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.spinnermenu, menu);
spinnerlist = new ArrayList<String>();
spinnerlist.add("Items1");
spinnerlist.add("Items2");
spinneradapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerlist);
Spinner s = (Spinner) menu.findItem(R.id.menuSort).getActionView();
s.setAdapter(spinneradapter);
super.onCreateOptionsMenu(menu, inflater);
}
}
I am getting error in this line
setHasOptionsMenu(true);
and Null exception in this line
s.setAdapter(spinneradapter);
Could any one tell me how to rectify this error?
*PS : Is there any way to do the same?*