Create a navigation bottom view for every child of the fragment - android

Hi I am new to Android so if my question seems redundant, please bear with me as I was unable to find a proper answer anywhere. I have a main activity with 4 tabs on the bottom navigation bar and three fragments to populate these tabs. Now when I start a child of any of these fragments, the child is not displayed with the navigation bar. How do i achieve this?
MainActivity.class main function
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
// BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = TabOneFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = TabTwoFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = TabThreeFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace( R.id.frame_layout,selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, TabOneFragment.newInstance());
transaction.commit();
TabActivity
public class TabOneFragment extends Fragment {
ArrayList<SettingsClass> data;
private Button send;
ListView listView;
public static TabOneFragment newInstance() {
TabOneFragment fragment = new TabOneFragment();
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_tab_one_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable final Bundle savedInstanceState) {
data = new ArrayList<>();
data.add(new SettingsClass("Option1", R.drawable.o1));
data.add(new SettingsClass("Option2", R.drawable.o2));
listView = view.findViewById(R.id.listView);
MyAdapter adapter = new MyAdapter(getActivity().getApplicationContext(), data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(getActivity().getApplicationContext(),ChildActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "NO_CONTACT"));
startActivity(intent);
break;
}
}
}
});
The ChildActivity is not created with the navigation bottom tab. Can anybody guide me??
layout for tab one:
<?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_main"
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"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView">
</ListView>
</RelativeLayout>

Related

Get data from fragment and send it to activity

I have an activity in which i desire to retrieve data (the text in some edit texts) when i click a button in my toolbar :
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
RETRIEVE EDITTEXT!!
break;
}
this is my activity :
public class ViatgeDetallTransportActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
}
And my fragment class :
public class ViatgeDetallTransportFragment extends Fragment {
public static final String ARG_ID = "id";
public ViatgeDetallTransportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
return rootView;
}
}
With a simple layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/layout_fragment_transportation" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Transportation"
/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTitleFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtDescripcioFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
</LinearLayout>
In the activity, when I click the toolbar button "mnufragmentOk" i want to recieve the data in the edit texts, so i can create a custom object.
Keep the fragment instance as a global variable in Activity
public class ViatgeDetallTransportActivity extends AppCompatActivity{
ViatgeDetallTransportFragment fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
String s=fragment.getFirstEditTextData();
break;
}
}
Impliment the getFirstEditTextData() method inside of your Fragment
You can set a TAG for your fragment:
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment, "MyFragment").commit();
Then you can find that instance when you click the button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
break;
}
Finally, you can find the TextView and get it's value:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
EditText editText = (EditText)fragment.getView().findViewById(R.id.my_text_view);
String string = editText.getText().toString().trim();
break;
}
plus:
don't forget to set an ID to your EditTexts:
<EditText
android:id="#+id/my_edit_text"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
and you need to reference them in your fragment's view creation:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
EditText editText = (EditText)rootView.findViewById(R.id.my_edit_text);
return rootView;
}

Android - display ListView in TabLayout

I've created an app that utilizes ListView and now I would like to display in a TabLayout, I've Googled this but none of the suggested solutions worked properly.
The tab layout itself is built as so:
PageAdapter
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
AllTasksTabFragment tab1 = new AllTasksTabFragment();
return tab1;
case 1:
WaitingTasksTabFragment tab2 = new WaitingTasksTabFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
AllTasksTabFragment
public class AllTasksTabFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.all_tasks, container, false);
}
}
Main Layout
<?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: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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="il.ac.shenkar.david.todolistex2.Main2Activity"
tools:showIn="#layout/activity_main2">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
AllTasks tab layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/Main2ActivitylinearLayout3">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="right"
android:paddingRight="10dp"
android:text=""
android:id="#+id/totalTask"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:id="#+id/Main2ActivitylinearLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:paddingRight="8dp"
android:text="Sort:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/sort_array"
android:id="#+id/sortSpinner"
android:gravity="center"
android:textAlignment="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/Main2ActivitylinearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="No Tasks to Display"
android:layout_marginTop="60dp"
android:layout_marginLeft="60dp"
android:id="#+id/emptylist"
android:gravity="center"
android:layout_centerHorizontal="true"
android:textStyle="bold" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alltab_emptylist"
android:layout_centerHorizontal="true" />
</LinearLayout>
Main Activity OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbM = DBManager.getInstance(context);
total_tasks_text = (TextView) findViewById(R.id.totalTask);
if(Globals.diffusr)
{
dbM.clearDB();
}
//check if any tasks exist in Parse DB
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Task");
query.whereEqualTo("TeamName", Globals.team_name);
if (Globals.IsManager == false) {
SharedPreferences sharedpreferences = getSharedPreferences("il.ac.shenkar.david.todolistex2", Context.MODE_PRIVATE);
query.whereEqualTo("Employee", sharedpreferences.getString("LoginUsr", null));
//if not manager disable action button
FloatingActionButton fbtn = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fbtn.getLayoutParams();
p.setBehavior(null); //should disable default animations
p.setAnchorId(View.NO_ID); //should let you set visibility
fbtn.setLayoutParams(p);
fbtn.setVisibility(View.GONE);
}
itemListAllTasks = new ArrayList<Task>();
itemListWaitingTasks = new ArrayList<Task>();
all_list = (ListView) findViewById(R.id.alltasks_listView);
waiting_list = (ListView) findViewById(R.id.waitingtasks_listView);
try {
tsks = query.find();
for (ParseObject tmp : tsks) {
tmp_task = new Task();
tmp_task.setDescription(tmp.getString("Description"));
int position = tmp.getInt("Category");
switch (position) {
case 0:
tmp_task.setTask_catg(Category.GENERAL);
break;
case 1:
tmp_task.setTask_catg(Category.CLEANING);
break;
case 2:
tmp_task.setTask_catg(Category.ELECTRICITY);
break;
case 3:
tmp_task.setTask_catg(Category.COMPUTERS);
break;
case 4:
tmp_task.setTask_catg(Category.OTHER);
break;
}
position = tmp.getInt("Priority");
switch (position) {
case 0:
tmp_task.setPriority(Priority.LOW);
break;
case 1:
tmp_task.setPriority(Priority.NORMAL);
break;
case 2:
tmp_task.setPriority(Priority.URGENT);
break;
default:
tmp_task.setPriority(Priority.NORMAL);
break;
}
position = tmp.getInt("Status");
switch (position) {
case 0:
tmp_task.setTask_sts(Task_Status.WAITING);
break;
case 1:
tmp_task.setTask_sts(Task_Status.INPROGESS);
break;
case 2:
tmp_task.setTask_sts(Task_Status.DONE);
break;
default:
tmp_task.setTask_sts(Task_Status.WAITING);
break;
}
position = tmp.getInt("Location");
switch (position) {
case 0:
tmp_task.setTsk_location(position);
break;
case 1:
tmp_task.setTsk_location(position);
break;
case 2:
tmp_task.setTsk_location(position);
break;
case 3:
tmp_task.setTsk_location(position);
break;
case 4:
tmp_task.setTsk_location(position);
break;
default:
tmp_task.setTsk_location(position);
break;
}
tmp_task.setDueDate(tmp.getDate("DueDate"));
tmp_task.setParse_task_id(tmp.getObjectId());
tmp_task.setEmp_name(tmp.getString("Employee"));
syncTaskList(tmp_task);
}
} catch (ParseException e) {
}
itemListAllTasks = dbM.getAllTasks();
all_list.setAdapter(new TaskItemAdapter(context, itemListAllTasks));
itemListWaitingTasks = dbM.getSortedTasks(Sorting.fromInteger(Sorting.WAITING.ordinal()));
waiting_list.setAdapter(new TaskItemAdapter(context, itemListWaitingTasks));
all_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long arg3) {
//get item instance from list
Task tt = (Task) ((TaskItemAdapter) parent.getAdapter()).getItem(position);
if (Globals.IsManager == true) {
Globals.temp = tt.getTsk_location();
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), EditTaskActivity.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_UPDATE_TASK);
}
if (Globals.IsManager == false) {
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), ReportTaskStatus.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_EMP_VIEW_TASK);
}
return false;
}
});
waiting_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long arg3) {
//get item instance from list
Task tt = (Task) ((TaskItemAdapter) parent.getAdapter()).getItem(position);
if (Globals.IsManager == true) {
Globals.temp=tt.getTsk_location();
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), EditTaskActivity.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_UPDATE_TASK);
}
if (Globals.IsManager == false) {
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), ReportTaskStatus.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_EMP_VIEW_TASK);
}
return false;
}
});
all_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(context, "Long press to edit task", Toast.LENGTH_SHORT).show();
}
});
waiting_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(context, "Long press to edit task", Toast.LENGTH_SHORT).show();
}
});
emptylist_txt = (TextView) findViewById(R.id.alltab_emptylist);
if (itemListAllTasks.size() == 0) {
emptylist_txt.setVisibility(View.VISIBLE);
total_tasks_text.setVisibility(View.GONE);
} else {
emptylist_txt.setVisibility(View.GONE);
total_tasks_text.setVisibility(View.VISIBLE);
total_tasks_text.setText("");
total_tasks_text.setText("Total " + itemListAllTasks.size());
}
sorts = getResources().getStringArray(R.array.sort_array);
sort_selector = (Spinner) findViewById(R.id.sortSpinner);
sortSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sorts);
sortSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sort_selector.setAdapter(sortSpinnerAdapter);
sort_selector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
Globals.last_sort = position;
SortTaskList(position);
}
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Spinner1:no selection", Toast.LENGTH_SHORT).show();
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("All Tasks"));
tabLayout.addTab(tabLayout.newTab().setText("Waiting"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
How should I do this when using tabs?
I have two tabs - AllTasks (which is displayed here) & Waiting (which is build in the same way).
How do I sent the ListView for each of them? So when a user transitions between tabs, the correct list will be displayed.
First Remove this listener from your activity code tabLayout.setOnTabSelectedListener . Then carry out like this.
Interface:
public interface DavidInterface
{
List<Task> getListData(int position);
}
PageAdapter;
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new yourOwnFragment();
Bundle bundle = new Bundle();
bundle.putInt("position",position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return mNumOfTabs;
}
MainActivityOnCreate:
class MainActivity extends AppcompatActivity implements DavidInterface
{
Hashmap<Integer,List<Task>> task_list_map = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
task_list_map.add(listitem1);
task_list_map.add(listitem2);
}
//Interface method.
#Override
public List<Task> getListData(int position)
{
return task_list_map.get(position);
}
TabFragment:
public class AllTasksTabFragment extends Fragment
{ DavidInterface davidinterface;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.all_tasks, container, false);
davidinterface = (DavidInterface)getActivity();
Bundle bundle = getArguments();
int pager_position = bundle.getInt("position",position);
List<Task> task = davidinterface.getListData(pager_position);
//populate this data in your listview inside this fragment layout.
}
}
My fragment code
R.layout.second_fragment it's layout with listview
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.second_fragment, container, false);
listView = (ListView) v.findViewById(R.id.times_listView);
return v;
}

Switching fragments in navigation drawer on item click

I added a navigation drawer in my app and creates a list of fragments Home,Mobiles,laptops in it. When I ran the app the main activity content launched on start. What I need now is when I click on the items in the navigation drawer it opens the fragment layout but the main content is also displayed, how can I hide the main content when a fragment item is clicked.
This is the code
MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
};
private ShareActionProvider shareActionProvider;
private String[] titles;
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private int currentPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myApp = getApplication();
// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");
// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
lv.setVerticalFadingEdgeEnabled(true);
// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
lv.setAdapter(adapter);
titles = getResources().getStringArray(R.array.titles);
drawerList = (ListView)findViewById(R.id.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Populate the ListView
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, titles));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
//Display the correct fragment.
if (savedInstanceState != null) {
currentPosition = savedInstanceState.getInt("position");
setActionBarTitle(currentPosition);
} else {
selectItem(0);
}
// Set on item click listener to the ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
Intent intent = new Intent(MainActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);
}
});
//Create the ActionBarDrawerToggle
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.string.open_drawer, R.string.close_drawer) {
//Called when a drawer has settled in a completely closed state
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
//Called when a drawer has settled in a completely open state.
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
FragmentManager fragMan = getSupportFragmentManager();
Fragment fragment = fragMan.findFragmentByTag("visible_fragment");
if (fragment instanceof TopFragment) {
currentPosition = 0;
}
if (fragment instanceof MobileFragment) {
currentPosition = 1;
}
if (fragment instanceof LaptopFragment) {
currentPosition = 2;
}
if (fragment instanceof StoresFragment) {
currentPosition = 3;
}
setActionBarTitle(currentPosition);
drawerList.setItemChecked(currentPosition, true);
}
}
);
}
private void selectItem(int position) {
// update the main content by replacing fragments
currentPosition = position;
Fragment fragment;
switch(position) {
case 1:
fragment = new MobileFragment();
break;
case 2:
fragment = new LaptopFragment();
break;
case 3:
fragment = new StoresFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment, "visible_fragment");
ft.addToBackStack(null);
// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Set the action bar title
setActionBarTitle(position);
//Close drawer
drawerLayout.closeDrawer(drawerList);
}
#Override
protected void onDestroy() {
super.onDestroy();
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public ImageLoader imageLoader;
public CustomListAdapter(MainActivity activity) {
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// Set the total list item count
return feed.getItemCount();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item, null);
}
// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvDate = (TextView) listItem.findViewById(R.id.date);
// Set the views in the layout
imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvDate.setText(feed.getItem(pos).getDate());
return listItem;
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", currentPosition);
}
private void setActionBarTitle(int position) {
String title;
if (position == 0) {
title = getResources().getString(R.string.app_name);
} else {
title = titles[position];
}
getSupportActionBar().setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
setIntent("This is example text");
return super.onCreateOptionsMenu(menu);
}
private void setIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
shareActionProvider.setShareIntent(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_create_order:
//Code to run when the Create Order item is clicked
Intent intent = new Intent(this, OrderActivity.class);
startActivity(intent);
return true;
case R.id.action_settings:
//Code to run when the settings item is clicked
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
activity_main:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context="com.example.ayush.gadgetguru.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<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>
<include layout="#layout/content_main" />
</LinearLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
<ListView android:id="#+id/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="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
TopFragment.java:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TopFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_top, container, false);
}
}
fragment_top.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1" >
</ListView>
</FrameLayout>

Navigating to the view pager tab from an activity

I am creating an android application which uses viewpager and PageSlidingTabLibrary.It has 4 tabs and each tab has a list view inside it.when the list view item is clicked a new activity opens and shows the details of the item clicked.The new activity has a back button in action bar to previous activity(ie MainActivity) in which tab view is present.
The problem is if the navigation to other activity is from second tab after comeback to the MainActivity the second tab should be shown but it doesn't happend it will go to the first tab.How can i get it done Help me.
Here is my code
xml layout
<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"
tools:context=".MainActivity"
android:orientation="vertical"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
app:pstsDividerColor="#ff1abc9c"
app:pstsIndicatorColor="#ff1abc9c"
app:pstsIndicatorHeight="5dp"
app:pstsDividerPadding="5dp"
android:keepScreenOn="true"
app:pstsShouldExpand="true"
app:pstsUnderlineColor="#ff1abc9c"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/content"
android:layout_height="match_parent"
android:layout_width="match_parent">
<!--you can put your existing views of your current xml here, so yes your entire xml is now inside this FrameLayout -->
</FrameLayout>
</android.support.v4.view.ViewPager>
</LinearLayout>
and Activity file
public class MainActivity extends FragmentActivity{
ViewPager pager;
PagerSlidingTabStrip tabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager= (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
tabStrip= (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setViewPager(pager);
Log.d("msg","Oncreate in main activity called");
if(savedInstanceState!=null)
{
onRestoreInstanceState(savedInstanceState);
}
}
public class MyPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTitleProvider
{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return "Events";
case 1:
return "Users";
case 2:
return "Groups";
case 3:
return "Settlement";
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new EventFragment();
case 1:
return new UserFragment();
case 2:
return new GroupFragment();
case 3:
return new SettlementFragment();
}
return null;
}
#Override
public int getPageIconResId(int position) {
switch(position)
{
case 0:
return R.drawable.event;
case 1:
return R.drawable.user;
case 2:
return R.drawable.group;
case 3:
return R.drawable.settlement;
}
return 0;
}
}
}
Fragment class
public class EventFragment extends ListFragment {
String[] events={"Trip to Goa","Trip to Ooty"};
public EventFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ListView eventlist=new ListView(getActivity());
eventlist.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
eventlist.setId(android.R.id.list);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,events);
setListAdapter(adapter);
return eventlist;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("Tabno",1);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent expense = new Intent();
expense.setClass(getActivity(), ExpenseActivity.class);
startActivity(expense);
Bundle eventbundle=new Bundle();
eventbundle.putInt("Tabno",1);
onSaveInstanceState(eventbundle);
}
}
On your next activity add these codes :
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
Override your device's back button:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
Just override the back button in your activity details:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
And it will shows the correct fragment in the viewpager

Android - Navigation drawer fragments

I have implemented navigation drawer in my android app. but now I want to be able to change the layout using fragments when the user clicks any list item in the navigation bar.
Here is what I have got so far:
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="220dp"
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>
Java File
public class MainActivity extends Activity {
final String[] data ={"one","two","three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
}
});
drawer.closeDrawer(navList);
}
});
}
}
Using the above code, I implemented navigation drawer in my app and I see "one", "two" and "Three" list items in the navigation drawer but nothing happens when I click on them except the drawer closes.
So, my question is :
How do I add the fragment functionality to the above given code?
I am beginner. Thanks in advance!
On click have
selectItem(pos);
Then
public void selectItem(int position)
{
switch(position)
{
case 0:
// fragment1
// use fragment transaction and add the fragment to the container
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment = new Fragment1();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
break;
case 1:
// fragment2
break;
case 2:
// fragment2
break;
}
}
use This:
public class MenuFragmentActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_layout);
addFragments(new Sample(), false, false,
AndyConstants.CONTENT_PAGE);
}
public void addFragments(Fragment fragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.anim.fragment_from_right,
R.anim.fragment_from_left, R.anim.fragment_from_right,
R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
For Fragment:
public class Sample extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.page, container, false);
return view;
}
}
After generate a Navigation Drawer Activity by File->New->Activity->Navigation Drawer Activity, here are 3 steps
First, go to app_bar_main.xml then
replace
<include layout="#layout/content_main"/>
by
<FrameLayout
android:id="#+id/frame_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
Second, go to MainActivity -> onNavigationItemSelected then modify it like
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = CameraFragment.newInstance();
} else if (id == R.id.nav_gallery) {
fragment = GalleryFragment.newInstance();
} else if (id == R.id.nav_slideshow) {
fragment = SlideShowFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();
setTitle(item.getTitle());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Finally, create Fragment class, example a Fragment
public class CameraFragment extends Fragment{
public static CameraFragment newInstance() {
Bundle args = new Bundle();
CameraFragment fragment = new CameraFragment();
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_camera, null, false);
return rootView;
}
}
Demo project

Categories

Resources