Navigation Drawer opens to different fragments - android-fragments

I am a beginner when it comes to Android. I have spent hours reading tutorials, watching videos, and combing through stackoverflow trying to figure this out. Even with all the online resources available , I still can't figure this out.
I want my list view always on the main screen, but when I swipe I want the navigation drawer to slide in and display a different fragment depending on which item in the list view has been selected. For example if the user selected 'account', when they slide from the right the account fragment would display.
I've left in 'navList' and 'nav2List' for testing, but I would like these to be fragments.
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bankMenu"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</ListView>
</RelativeLayout>
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
<ListView
android:id="#+id/nav2List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
JAVA
public class MainActivity extends AppCompatActivity {
private ListView menu;
private ListView mDrawerList;
private ListView secondDrawerList;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = (ListView) findViewById(R.id.bankMenu);
mDrawerList = (ListView)findViewById(R.id.navList);
secondDrawerList = (ListView)findViewById(R.id.nav2List);
addBankingListItems(); // populate the banking items list
menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) menu.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
if (itemPosition < 4) { // TESTING FUNCTIONALITY
addDrawerItems();
} else {
addSecondDrawerItems();
}
}
});
}
---EDIT---
This issue has been resolved.
In the xml file, i changed the two ListViews to a RelativeView.
<RelativeLayout
android:id="#+id/frame_to_be_replaced"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_below="#+id/topRL"
android:background="#ffeeeeee">
</RelativeLayout>
In the MainActivity, I created a fragment manager, then after my switch statement, i replaced the frame with the required one. Hope this can help someone, send me a pm for more info.
FragmentManager fragmentManager = getFragmentManager();
switch (itemPosition) {
case 0:
fragment = MyFrag1.newInstance("", ""); // fragment declared above
break;
case 1:
fragment = MyFrag2.newInstance("", "");
break;
case 2: etc....
fragmentManager.beginTransaction()
.replace(R.id.frame_to_be_replaced, fragment)
.commit();

Related

Add tabs based on categories in Xamarin.Android

Suppose, I have N number categories which come from my REST. I want to add tabs for all of these categories. Let's see e.g. suppose in my REST response have only 2 categories it's create only two tab. if it has 5 categories then 5 tabs and so on.
And in each category tab load a list of my item for selected tab (category).
Currently I I’ve implement it with static data using fragment. Each fragment uses a list view for loading items. But I think it’s not a right way.
Here is an example
Can you please suggest me what should I use to or how can I add tab based on my category and load my list for each category? I haven’t found TabLayout in Xamarin.android.
My Main View:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentContainer" />
</LinearLayout>
Here is My Main Activity :
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.MainView);
ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
AddTab(" Favorite", Resource.Drawable.FavoritesIcon, new FavoriteItemFragment());
AddTab(" Ice", Resource.Drawable.IceCreamIcon, new IceCreamFragment());
AddTab(" Shushi", Resource.Drawable.SushiIcon, new ShushiFragment());
AddTab(" Burger", Resource.Drawable.VeggieLoversIcon, new BurgerFragment());
AddTab(" Biriyani", Resource.Drawable.BiriyaniIcon, new BiriyaniFragment());
AddTab(" Pasta", Resource.Drawable.PastaIcon, new PastaFragment());
AddTab(" Pizza", Resource.Drawable.PizzaIcon, new PizzaFragment());
AddTab(" Sandwich", Resource.Drawable.SandwichIcon, new SandwichFragment());
AddTab(" Coffee", Resource.Drawable.CoffeeIcon, new CoffeeFragment());
//no_of_categories = allCategories.Count;
}
private void AddTab(string tabText, int iconResourceId, Fragment view)
{
var tab = this.ActionBar.NewTab();
tab.SetText(tabText);
tab.SetIcon(iconResourceId);
tab.TabSelected += delegate (object sender, ActionBar.TabEventArgs e)
{
var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);
if (fragment != null)
{
e.FragmentTransaction.Remove(fragment);
}
e.FragmentTransaction.Add(Resource.Id.fragmentContainer, view);
};
tab.TabUnselected += delegate (object sender, ActionBar.TabEventArgs e)
{
e.FragmentTransaction.Remove(view);
};
this.ActionBar.AddTab(tab);
}
One of my Fragment View:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:background="#FCD972"
android:minHeight="25px">
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/itemListView" />
</LinearLayout>
And My Fragment Class:
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
FindViews();
HandleEvents();
items = itemDataService.GetItemsForCategory(4);
listView.Adapter = new ItemListAdapter(this.Activity, items);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.MyFragment, container, false);
}
Thank You
Can you please suggest me what should I use to or how can I add tab based on my category and load my list for each category? I haven’t found TabLayout in Xamarin.android.
I can't say the method you used is wrong, but if you want to use TabLayout in Xamarin.Android, you need to install the Xamarin.Android.Support.Design package together with some packages like Xamarin.Android.Support.v4.
Then you can design your layout for example like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
style="#style/TabLayoutThemes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
For more information, you can refer to this tutorial: Xamarin Android: Working with material design TabLayout and ViewPager.

Animate Toolbar Logo / Title changes when using with ViewPager Fragments

I am using ViewPager to host two fragments in my main activity. One fragment is intended to show app logo and other one just title on the Toolbar. I am able to do that without any issue.
However, I want to animate these changes when I swipe from one fragment to another using swipe on ViewPager, like Fade out the logo and fade in the title.
Any clue or idea how can I do it.
Ok, as per Amir's suggestion I tried it using the below layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/toolbar_logo_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:alpha="1"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo"
android:id="#+id/toolbar_logo_image"
android:alpha="1"
/>
</RelativeLayout>
<RelativeLayout
android:layout_toRightOf="#id/toolbar_log_container"
android:layout_alignWithParentIfMissing="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbar_info_container"
>
<ImageView
android:id="#+id/toolbar_profile_pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/one"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginRight="#dimen/value_12"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/toolbar_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextInfoName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/toolbar_profile_pic"
android:layout_toEndOf="#+id/toolbar_profile_pic"
android:layout_marginTop="#dimen/value_8"
/>
<android.support.v7.widget.AppCompatTextView
android:id="#+id/toolbar_user_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextInfoWork"
android:layout_below="#+id/toolbar_user_name"
android:layout_toRightOf="#+id/toolbar_profile_pic"
android:layout_toEndOf="#+id/toolbar_profile_pic"
android:layout_alignBottom="#id/toolbar_profile_pic"
/>
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
And it works ! But what if I would have to do it as per scroll position of the ViewPager. I tried placing the animation in
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
part of the code, but the animation runs uncontrollably, since this callback is called everytime once the scroll is started, irrespective of it is actually scrolled or not.
For Animating Toolbar you should define your own Toolbar something like this and for Animating elements of Toolbar in your MainActivity you can use something like following code:
getLeftIcon().animate()
.translationY(0)
.setDuration(300)
.setStartDelay(300);
getAppLogo().animate()
.translationY(0)
.setDuration(300)
.setStartDelay(400);
and for changing title due to ViewPager position just define listener for your ViewPager :
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Change your title here
}
});
Animation part of code available here.
Finally, here's what I did to achieve the desired effect:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private float prevPosition = 0.0f;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
///hold current position
if(prevPosition == 0) {
prevPosition = positionOffset;
return;
}
///check if prev position is equal to current one, avoid multiple calls
if(prevPosition == positionOffset) {
return;
}
/// zero position check
if(prevPosition >= 0.9) {
if(positionOffset == 0.0f) {
Logger.log_error("Do not hide infoHolder");
return;
}
}
//update previous position
prevPosition = positionOffset;
///animate title text and logoholder accordingly
logoHolder.animate().translationX(logoHolder.getWidth() -positionOffset * logoHolder.getWidth()) .alpha(positionOffset).setDuration(0).start();
mTitleText.animate().translationX(- positionOffset * mTitleText.getWidth()).alpha(1.0f - logoHolder.getAlpha()).setDuration(0).start();
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
The above code resulted in a smooth transition b/w Logo and title text when fragments are scrolled inside viewpager.
Posting the answer hoping this may help someone else.
Thanks Amir for the guidance.

switch between fragments without 'FragmentPagerAdapter'

I am trying to switch between fragments on my activity.
I was reading this tutorial, but my case is a bit different since I don't want/can't use the 'FragmentPagerAdapter', instead, I want that a button that is pressed on activity will switch between 2 fragments.
My activity layout consist of a Button and ViewPager. in Addition I have got Fragment1 and Fragment2.
How can I switch between this fragments using OnClick method?
My Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:text="Switch it"
android:onClick="switchFragment"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
and my activity:
public class MainHeaderFragment2 extends ActionBarActivity {
...
public void switchFragment(View view){
Fragment fragment
if(checkSomething())
fragment = new Fragment1();
else
fragment = new Fragment2();
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// now need to put the selected fragment in ViewPager somehow.
// How? that is my question
}
}
Based on your comments, this is what you should do:
Change your layout to this:
<Button
android:text="Switch it"
android:onClick="switchFragment"/>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
To populate it first time with your first fragment:
Fragment1 fragment1 = Fragment1.create();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment1);
fragmentTransaction.commit();
To replace it,
Fragment2 fragment2 = Fragment2.create();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment2, "optionalTag");
fragmentTransaction.commit();
Fragmen1 and Fragment2 are the fragments you want to display or replace.

android buttons to switch between two screens

I am a beginner of android application. I am using Android Studio to make an application for a shopping cart list. For the start, right now, I am working on the creating two buttons on each screens that called, "edit" and "save." So if I click the edit button, it will go to screen2, and if I click the save, it will go to screen1. However, Whenever I tried to lunch it, it's getting an error like this:
02-14 15:14:57.830 AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jieun.hw1, PID: 1782
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jieun.hw1/com.example.jieun.hw1.MainActivityOne}: java.lang.NullPointerException
My codes for two screens and the layouts are something like this:
Screen1:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button editButton = (Button) findViewById(R.id.e_button);
editButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent editScreen = new Intent(..MainActivityTwo.class);
startActivity(editScreen);
}
});
}
Screen2:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button saveButton = (Button) findViewById(R.id.s_button);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent saveScreen;
saveScreen = new Intent(getApplicationContext(), MainActivityOne.class);
startActivity(saveScreen);
}
});
}
Layout1:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivityOne">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:id="#+id/e_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
Layout2:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivityOne">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/s_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Have you tried looking through your code for screen 1?
Here:
//Starting a new Intent
Intent editScreen = new Intent(..MainActivityTwo.class);
startActivity(editScreen);
}
There are two periods before MainActivityTwo.class

Click on a specific part of an ImageView

I would like to be able to touch a specific part of an ImageView and display a toast.
Here is my xml file "dessintest.xml" :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relative1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="#+id/imageview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/dessin1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageButton
android:id="#+id/imageButton1"
android:background="#00000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/image" />
</RelativeLayout>
Then here is my main file "DessinTest.java" :
public class DessinTest extends Activity {
ImageButton imageButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.dessintest);
addListenerOnButton();
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.dessin1);
TouchImageView touch = new TouchImageView(this);
touch.setImageBitmap(bm);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton1);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(DessinTest.this,"Click !", Toast.LENGTH_SHORT).show();
}
});
}
}
When I try that, I can zoom the ImageView but I cannot see the ImageButton.
When I delete this bit of code (the one for the zooming of my ImageView) :
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.dessin1);
TouchImageView touch = new TouchImageView(this);
touch.setImageBitmap(bm);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
it is working, I can see the ImageButton and click on it.
What I would like is to have both functionnalities, click and zoom.
Thanks !
OK I resolved my problem by using this sample :
https://github.com/chrisbanes/PhotoView/blob/master/sample/src/uk/co/senab/photoview/sample/SimpleSampleActivity.java
I can now zoom and touch/detect specific parts of the screen. It works very well !

Resources