Navigating to the view pager tab from an activity - android

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

Related

Select Tab and run code in its fragment

I have a tab setup with a VeiwPager and a MainActivity. When one particular tab, "B" is selected I want to Show Fragment B user interface and start doing something.
The method I have found to do this is to use a LocalBroadcastReceiver in Fragment "B" and have it call a method. The broadcast is sent from Main Activity inside the onTabSelected method.
Is this a good approach?
Activity.xml
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Activity.class
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
setUpviewPager();
tabLayout.setupWithViewPager(viewPager);
}
private void setUpviewPager() {
ViewPagerAdpater viewPagerAdapter = new ViewPagerAdpater(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
}
private class ViewPagerAdpater extends FragmentPagerAdapter {
ViewPagerAdpater(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirsFrag();
case 1:
return new FirsFrag();
case 2:
return new FirsFrag();
default:
return null;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
return "Second Tab";
case 2:
return "Third Tab";
default:
return "";
}
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
Thanks, just run this code, this adapter is FragmentPagerAdpater

Create a navigation bottom view for every child of the fragment

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>

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;
}

Event Handler in multiple instances of the same Fragment in Android

I have a fragment which consists of a Button and a TextView. By clicking the button, I need to change the TextView. But I need to create 18 instances of that fragment and set it to a ViewPager. My problem is how to write the button handler. Because I failed to change the corresponding TextView when I click the button. And it always changed the TextView of the same pages, no matter which the current page is.My code is like below:
fragment_first.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.mycompany.redotgolf.FirstFragment">
<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="com.mycompany.redotgolf.HoleRecord">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/unfilled_red_circle"
android:id="#+id/par_button"
android:layout_below="#+id/par_label"
android:layout_centerHorizontal="true"
android:gravity="center_vertical|center|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par"
android:id="#+id/par_label"
android:textSize="40dp"
android:editable="false"
android:gravity="center"
android:layout_below="#+id/flag"
android:layout_centerHorizontal="true" />
</RelativeLayout>
FirstFragme.java
public class FirstFragment extends Fragment implements View.OnClickListener {
// Store instance variables
private String title;
private int page;
public ContentItem contentItem;
public static FirstFragment newInstance(int page, String title,ContentItem contentItem) {
FirstFragment fragmentFirst = new FirstFragment();
fragmentFirst.contentItem=contentItem;
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
v.setId(page);
View tv = v.findViewById(R.id.num_par);
((TextView)tv).setText(contentItem.par.toString());
return v;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.par_button: {
Integer par;
View view=getView();
TextView textView=(TextView)view.findViewById(R.id.num_par);
if((par=Integer.parseInt(textView.getText().toString()))<5){
par++;
contentItem.par++;
textView.setText(par.toString());
}else{
textView.setText("3");
contentItem.par=3;
}
System.out.println(par);
break;
}
}
}
}
HoleRecord.java
public class HoleRecord extends FragmentActivity {
public FragmentPagerAdapter adapterViewPager;
static ArrayList<ContentItem> contentItems=getSampleContent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hole_record);
// Retrieve the ViewPager from the content view
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
// Set an OnPageChangeListener so we are notified when a new item is selected
vp.setOnPageChangeListener(mOnPageChangeListener);
// Finally set the adapter so the ViewPager can display items
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vp.setAdapter(adapterViewPager);
vp.setCurrentItem(1);
adapterViewPager.getItem(1);
}
#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_hole_record, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 18;
//public FirstFragment f;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
FirstFragment f= FirstFragment.newInstance(position, "Page"+position,contentItems.get(position));
return f;
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
/* private final PagerAdapter mPagerAdapter = new PagerAdapter() {
LayoutInflater mInflater;
#Override
public int getCount() {
//return mItems.size();
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Just remove the view from the ViewPager
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Ensure that the LayoutInflater is instantiated
if (mInflater == null) {
mInflater =(LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Inflate item layout for images
View iv = (View) mInflater.inflate(R.layout.score_par_view, container, false);
// Add the view to the ViewPager
container.addView(iv);
return iv;
}
};*/
/**
* A OnPageChangeListener used to update the ShareActionProvider's share intent when a new item
* is selected in the ViewPager.
*/
private final ViewPager.OnPageChangeListener mOnPageChangeListener
= new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// NO-OP
}
#Override
public void onPageSelected(int position) {
//setShareIntent(position);
}
#Override
public void onPageScrollStateChanged(int state) {
// NO-OP
}
};
static ArrayList<ContentItem> getSampleContent() {
ArrayList<ContentItem> items = new ArrayList<ContentItem>();
for(int i=1;i<=18;i++) {
items.add(new ContentItem(i));
}
return items;
}
}
activity_hole_record.xml
<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: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="com.mycompany.redotgolf.HoleRecord">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
In above code, ContentItem class is used to store the value to be presented in the TextView

using google maps with swipe taps

I try to start a tab, which can be swiped. It works fine! But if I try to implement Google Maps, then it works unit I switch the tab and go to the map back. I get these kind of Error:
E/AndroidRuntime(25324): FATAL EXCEPTION: main
E/AndroidRuntime(25324): android.view.InflateException: Binary XML file line #21: Error inflating class fragment
I searched many times in google and couldn't find a solution.
This is the MainActivity class Code:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
GoogleMapOptions nMap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
Fragment f1 = new LayersDemoActivity2();
return f1;
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0: return "Timeline";
case 1: return "Chat";
case 2: return "Fh";
case 3: return "Mehr";
default: return "Section " + (position + 1);
}
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Tab 1 calls this Fragment
public class LayersDemoActivity2 extends Fragment implements OnItemSelectedListener {
private GoogleMap mMap;
private CheckBox mTrafficCheckbox;
private CheckBox mMyLocationCheckbox;
//neu hinzugekommen
private LocationClient locationclient;
private String TAG = this.getClass().getSimpleName();
//neu hinzugekommen
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.layers_demo, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.traffic)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateTraffic();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.my_location)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateMyLocation();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.button1)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
try{
LatLng hier = new LatLng(mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude());
Marker setzen = mMap.addMarker(new MarkerOptions().position(hier).title("Here I am!"));
}catch(Exception e){
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
Spinner spinner = (Spinner) getView().findViewById(R.id.layers_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getView().getContext(), R.array.layers_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
mTrafficCheckbox = (CheckBox) getView().findViewById(R.id.traffic);
mMyLocationCheckbox = (CheckBox) getView().findViewById(R.id.my_location);
setUpMapIfNeeded();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mMap != null) {
updateTraffic();
updateMyLocation();
}
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
//getView().Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void updateTraffic() {
if (!checkReady()) {
return;
}
mMap.setTrafficEnabled(mTrafficCheckbox.isChecked());
}
private void updateMyLocation() {
if (!checkReady()) {
return;
}
mMap.setMyLocationEnabled(mMyLocationCheckbox.isChecked());
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setLayer((String) parent.getItemAtPosition(position));
}
private void setLayer(String layerName) {
if (!checkReady()) {
return;
}
if (layerName.equals(getString(R.string.normal))) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (layerName.equals(getString(R.string.hybrid))) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (layerName.equals(getString(R.string.satellite))) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (layerName.equals(getString(R.string.terrain))) {
mMap.setMapType(MAP_TYPE_TERRAIN);
} else {
Log.i("LDA", "Error setting layer with name " + layerName);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
last but not least, this is layers_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<!-- A set of test checkboxes. -->
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#id/map"
android:background="#D000"
android:orientation="vertical"
android:padding="6dp" >
<Spinner
android:id="#+id/layers_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/traffic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTrafficToggled"
android:text="#string/traffic" />
<CheckBox
android:id="#+id/my_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMyLocationToggled"
android:text="#string/my_location" />
</LinearLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:onClick="tagOnMyLocation"
android:text="#string/tag_me" />
and the activity_main.xml layout
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I guess it has something to do with fragment, but I dont know how and I dont know why. Please help. :(
Just paste this method after oncreatview method
#Override
public void onDestroyView() {
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
super.onDestroyView();
}

Categories

Resources