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;
}
Related
I have a fragment named "Notification fragment" in which I want to show another fragment named "Watching Fragment" using Tab layout . When I run the app, the tab layout bar is visible but the fragments are not visible.
My Fragment inside which other fragments are to be shown (Notifications Fragment)
public class NotificationsFragment extends Fragment{
GridView listv;
FragmentAdapter fragmentAdapter;
private NotificationsViewModel notificationsViewModel;
private FragmentNotificationsBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
notificationsViewModel =
new ViewModelProvider(this).get(NotificationsViewModel.class);
binding = FragmentNotificationsBinding.inflate(inflater, container, false);
View root = binding.getRoot();
TabLayout tabLayout = root.findViewById(R.id.tabLayout);
ViewPager vp = root.findViewById(R.id.vp2);
fragmentAdapter = new FragmentAdapter(getChildFragmentManager() , tabLayout.getTabCount());
vp.setAdapter(fragmentAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
vp.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 0 || tab.getPosition() == 1 || tab.getPosition() == 2)
fragmentAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
vp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return root; }
My First Fragment (Watching Fragment)
public class WatchingFragment extends Fragment {
ArrayList<String> list = new ArrayList<String>();
GridView gridv1;
private WatchingViewModel mViewModel;
public static WatchingFragment newInstance() {
return new WatchingFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.watching_fragment, container, false);
gridv1 = view.findViewById(R.id.gridv1);
Intent intent = getActivity().getIntent();
String animename = intent.getStringExtra("nameanime");
list.add(animename);
loadData2();
saveData2();
ListNewAdapter adapter = new ListNewAdapter(getContext(), R.layout.watch_list, list);
gridv1.setAdapter(adapter);
gridv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
list.remove(position);
adapter.notifyDataSetChanged();
saveData2();
return true;
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(WatchingViewModel.class);
// TODO: Use the ViewModel
}
private void saveData2() {
SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
ed.putString("anime list", json);
ed.apply();
}
private void loadData2() {
SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("anime list", "");
Type type = new TypeToken<ArrayList<String>>() {}.getType();
list = gson.fromJson(json , type);
if (list == null) {
list = new ArrayList<String>();
}
}
}
My View pager adapter
public class FragmentAdapter extends FragmentPagerAdapter {
int tabcount;
public FragmentAdapter(#NonNull #NotNull FragmentManager fm, int behavior) {
super(fm, behavior);
tabcount = behavior;
}
#NonNull
#NotNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new WatchingFragment();
case 1: return new CompletedFragment();
case 2: return new WantToWatchFragment();
default: return null;
}
}
#Override
public int getCount() {
return 0;
}
}
Notifications Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.notifications.NotificationsFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Watching" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Completed" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Want To Watch" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/vp2"
android:name="com.example.animeguide.ui.notifications.NotificationsFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
Watching Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ui.notifications.FragmentsInsideList.watching.WatchingFragment">
<TextView
android:id="#+id/textView4"
android:layout_width="184dp"
android:layout_height="58dp"
android:text="hello world"
android:textSize="34sp" />
<GridView
android:id="#+id/gridv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2" />
</LinearLayout>
In order for the Adapter to know how many pages it has, you need to override getCount method. You did override it, but used 0 as the number of pages, thus having no pages.
In your FragmentAdapter class, try changing this:
#Override
public int getCount() {
return 0;
}
To this:
#Override
public int getCount() {
return tabcount;
}
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>
I am new to Android and am trying a sample application for showing ViewPagers in a Master-Detail Flow using custom PagerAdapters and FragmentStatePagerAdapters. My application has a list of dummy items managed by a SQLiteDatabase which contain a title String, a description String, a Boolean like status, and a list of images (I plan to implement them as downloading from String urls but presently I'm just trying with a single image resource). I am having two problems in the Detail View.
My intention is to use a ViewPager with a FragmentStatePagerAdapter to show the detail view, which consists of a ViewPager with a custom PagerAdapter for showing the list of images, TextView for title and description, a ToggleButton for the like status and a delete button for deleting items from the list.
Issues:
The ViewPager with the custom PagerAdapter does not display the image. It occupies the expected space and swipes performed on it also behave as expected. Only the image is not visible.
[RESOLVED] On using the delete button, I am able to delete the item from the database, and also update the Master View accordingly, but I am not able to update the Detail View, and the app crashes.
Here is my code:
Code that calls ItemDetailActivity.java
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(getContext(), ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_LIST_POSITION, holder.position);
getContext().startActivity(detailIntent);
}
ItemDetailActivity.java
public class ItemDetailActivity extends FragmentActivity {
static ItemDetailPagerAdapter idpa;
static ViewPager detailPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
idpa = new ItemDetailPagerAdapter(getSupportFragmentManager());
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
detailPager = (ViewPager) findViewById(R.id.item_detail_container);
detailPager.setAdapter(idpa);
detailPager.setCurrentItem(getIntent().getIntExtra(ItemDetailFragment.ARG_LIST_POSITION, 0));
}
}
activity_item_detail.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.trial.piclist.ItemDetailActivity"
tools:ignore="MergeRootFrame" />
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
public static final String ARG_LIST_POSITION = "list_index";
public static final String ARG_TWO_PANE = "is_two_pane";
int position = -1;
long id = -1;
boolean twoPane = false;
ViewPager pager;
private PicItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
twoPane = getArguments().getBoolean(ARG_TWO_PANE, false);
position = getArguments().getInt(ARG_LIST_POSITION, -1);
id = getArguments().getLong(ARG_ITEM_ID, -1);
if (id == -1)
id = ItemListFragment.getIdByPosition(position);
setmItem(id);
}
public void setmItem(long id) {
if (id >= 0) {
try {
ItemListActivity.lds.open();
mItem = ItemListActivity.lds.getById(id);
ItemListActivity.lds.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (mItem != null) {
List<String> pics = new ArrayList<String>();
pics.add("1");
pics.add("2");
pics.add("3");
pics.add("4");
pics.add("5");
mItem.setPics(pics);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
DetailViewHolder holder = new DetailViewHolder();
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),
inflater, position);
pager.setAdapter(adapter);
holder.position = getArguments().getInt(ARG_LIST_POSITION);
holder.ttv = (TextView) rootView.findViewById(R.id.item_title);
holder.dtv = (TextView) rootView.findViewById(R.id.item_detail);
holder.likeButton = (ToggleButton) rootView
.findViewById(R.id.item_like);
holder.deleteButton = (Button) rootView.findViewById(R.id.item_delete);
rootView.setTag(holder);
if (mItem != null) {
holder.ttv.setText(mItem.getTitle());
holder.dtv.setText(mItem.getDescription());
holder.likeButton.setChecked(mItem.getIsLiked());
holder.likeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.toggleLike(mItem.getId());
mItem.toggleIsLiked();
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.toggleLiked(position);
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.removeItem(mItem.getId());
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.remove(position);
ItemListActivity.idpa.notifyDataSetChanged();
// What do I do so that the FragmentStatePagerAdapter is
// updated and the viewpager shows the next item.
}
});
}
return rootView;
}
static private class DetailViewHolder {
TextView ttv;
TextView dtv;
ToggleButton likeButton;
Button deleteButton;
int position;
}
}
fragment_item_detail.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:orientation="vertical"
android:padding="16dp"
tools:context="com.trial.piclist.ItemDetailFragment" >
<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="200dip">
</android.support.v4.view.ViewPager>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/item_title"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textIsSelectable="true" />
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/controls_layout" />
</TableRow>
<ScrollView
android:id="#+id/descScrollView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
</ScrollView>
</LinearLayout>
controls_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ToggleButton
android:id="#+id/item_like"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_gravity="right"
android:background="#android:drawable/btn_star"
android:gravity="center"
android:text="#string/like_list_item"
android:textOff="#string/empty_text"
android:textOn="#string/empty_text" />
<Button
android:id="#+id/item_delete"
style="?android:attr/buttonStyleSmall"
android:layout_width="30dip"
android:layout_height="30dip"
android:background="#android:drawable/ic_menu_delete"
android:text="#string/empty_text" />
</LinearLayout>
Custom PagerAdapter
ImagePagerAdapter.java
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
List<View> layouts = new ArrayList<>(5);
// Constructors.
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (layouts.get(position) != null) {
return layouts.get(position);
}
View layout = inflater.inflate(R.layout.detail_image,
((ViewPager) container), true);
try {
ImageView loadSpace = (ImageView) layout
.findViewById(R.id.detail_image_view);
loadSpace.setBackgroundColor(0x000000);
loadSpace.setImageResource(R.drawable.light_grey_background);
loadSpace.setAdjustViewBounds(true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
layout.setTag(images.get(position));
layouts.set(position, layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (((View) object).findViewById((view.getId())) != null);
}
}
FragmentPagerAdapter
ItemDetailPagerAdapter.java
public class ItemDetailPagerAdapter extends FragmentStatePagerAdapter {
public ItemDetailPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putLong(ItemDetailFragment.ARG_ITEM_ID, ItemListFragment.getIdByPosition(position));
args.putInt(ItemDetailFragment.ARG_LIST_POSITION, position);
args.putBoolean(ItemDetailFragment.ARG_TWO_PANE, ItemListActivity.mTwoPane);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
openDatabase();
int c = database.getCount();
closeDatabase();
return c;
}
#Override
public int getItemPosition(Object object) {
long mId = ((ItemDetailFragment) object).getmId();
int pos = POSITION_NONE;
openDatabase();
if (database.contains(mId)) {
pos = database.getPositionById(mId);
}
closeDatabase();
return pos;
}
}
Any help is much appreciated. Thanks :)
In your ItemDetailFragment, remove the viewpager from the holder, it should be directly into the returned view, something like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),inflater, position);
pager.setAdapter(adapter);
return rootView;
}
and the ViewHolder pattern should be applied inside your PagerAdapter.
In ImagePagerAdapter.java, correct the isViewFromObject method -
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (View) object);
}
This will correct the issue of the ImageView.
In ItemDetailPagerAdapter.java, override the getItemPosition method -
#Override
public int getItemPosition(Object object) {
int ret = POSITION_NONE;
long id = ((ItemDetailFragment) object).getId();
openDatabase();
if (databaseContains(id)) {
ret = positionInDatabase(id);
}
closeDatabase();
return ret;
}
On deleting call the FragmentStatePagerAdapter.NotifyDataSetChanged() method. This will make the Adapter update itself on deleting.
Although, the FragmentStatePagerAdapter uses a list of Fragments and of stored states to implement the adapter. That is also causing trouble. To remove that, implement your own list of Fragments.
I develope currently a small sample app with fragments and a viewPager. The viewPager shows 3 pages. In each page i instantiate a fragment of the same type. The fragment contains a textView and a button. On button click I want to replace the current fragment with another one. Now my problem is, no matter which button I press only the fragment of page 1 gets replaced. I dont know what I have to do in my pageAdapter class but I guess it has to do with using the same fragment and layout. I think I have to make sure, that my pageAdapter updates the correct page, but how do I achieve that?
For a better understanding why I want to achieve that, that I receive a json string within 3 node of type menu and I want to use each of them as a page in my viewPager.
Can someone show me a short and easy example for such a behavior? I think its a basic approach, so it cant be so difficult.
--------Edit---------
Here is the code:
public class FragmentPagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
public MyAdapter getmAdapter() {
return mAdapter;
}
public ViewPager getmPager() {
return mPager;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getFragmentManager(), this);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setOffscreenPageLimit(NUM_ITEMS + 2);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
}
}
MyAdapter:
public MyAdapter(FragmentManager fm, FragmentPagerSupport fragmentPagerSupport) {
super(fm);
this.fragmentPagerSupport = fragmentPagerSupport;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
Fragment newInstance = null;
switch (position) {
case 0:
newInstance = frag1.newInstance(position);
break;
case 1:
newInstance = frag1.newInstance(position);
break;
case 2:
newInstance = frag2.newInstance(position);
break;
case 3:
newInstance = frag2.newInstance(position);
break;
}
return newInstance;
}
Frag1 & Frag2 & ListItemFrag:
public static class frag1 extends ListFragment {
int mNum;
static frag1 newInstance(int num) {
frag1 f = new frag1();
Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class frag2 extends ListFragment {
int mNum;
static frag2 newInstance(int num) {
frag2 f = new frag2();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class ListItemFragment extends Fragment {
String itemName;
static ListItemFragment newInstance(String itemName) {
ListItemFragment i = new ListItemFragment();
Bundle args = new Bundle();
args.putString("text", itemName);
i.setArguments(args);
return i;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemName = getArguments() != null ? getArguments().getString("text") : "NULL";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_item, container, false);
View tv = v.findViewById(R.id.textView1);
((TextView) tv).setText("Cheese: " + itemName + " selected!");
return v;
}
}
Pager Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button
android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first" />
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="last">
</Button>
</LinearLayout>
Frag1 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
Frag2 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test2">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root2" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
ListItemFrag Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="230dp"
android:background="#AA33EE"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Hi I was facing same kind of issue. I fixed the issue by using
getChildFragmentManager().beginTransaction()
instead of
getActivity().getSupportFragmentManager().beginTransaction()
As in this case we are trying to make transaction from within a fragment (one out of the list of fragments which are attached to the ViewPager, thus the Activity holding the ViewPager) so we have to use getChildFragmentManager() here for desired results.
NOTE: I am using android support v4 library and thus corresponding FragmentManager.
I want to share TextView content which is displayed on ViewPager via
FragmentPagerAdapter but when I share the content it share previously
focused TextView Content.
When I click on Share button it share the content of the last
Fragment from which I came on current Fragment.
My Code
Share.java
public class Share extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
static int pages=4;
Button share;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.vpShare);
mPager.setAdapter(mAdapter);
share=(Button)findViewById(R.id.btShare);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView textView = (TextView) findViewById(R.id.tv);
String string = textView.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, string);
startActivity(Intent.createChooser(intent, "Share with:"));
}
});
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return pages;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ShowFragment1();
case 1:
return new ShowFragment2();
case 2:
return new ShowFragment3();
case 3:
return new ShowFragment4();
default:
return null;
}
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/vpShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/sunset" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/btShare"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="Share" />
</LinearLayout>
</LinearLayout>
screen_slide.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textStyle="italic" />
</ScrollView>
ShowFragment1.java
public class ShowFragment1 extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.screen_slide, container, false);
TextView textView = (TextView) view.findViewById(R.id.tv);
textView.setText("fragment1");
return view;
}
}
I got the solution of my problem
I have changed my Share.java class as follows..
Share.java
public class ShareNew extends FragmentActivity {
private MyPager mPager;
static int pages = 4;
Button share;
private TextView textView;
private int i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpagerlayout);
mPager = (MyPager) findViewById(R.id.myviewpager);
// mPager.setAdapter(mAdapter);
share = (Button) findViewById(R.id.btnShare);
for (i = 0; i < pages; i++) {
textView = new TextView(this);
switch (i) {
case 0:
textView.setText(R.string.share1);
break;
case 1:
textView.setText(R.string.share2);
break;
case 2:
textView.setText(R.string.share3);
break;
case 3:
textView.setText(R.string.share4);
break;
}
textView.setTag(i);
textView.setBackgroundColor(Color.BLUE);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
mPager.addPage(textView);
}
}
public void onShareText(View view) {
TextView tvShare;
tvShare = (TextView) mPager.findViewWithTag(mPager.getCurrentItem());
String string = tvShare.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, string);
startActivity(Intent.createChooser(intent, "Share with:"));
}
}