Tab Layout not showing fragments - android

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

Related

Handling ListView item clicks with ButterKnife

I am trying to handle item clicks on a listview using either the regular AdapterView.OnItemClickedListener or the ButterKnife #OnItemSelected annotation, but none of them work.
I have tried logging to see if any of the clicks come through by:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(Overview.class.getSimpleName(), String.valueOf(position));
}
and
#OnItemClick(R.id.tracks)
void onItemSelected(int position){
Log.e("Tracks", String.valueOf(position));
}
but none of them work. What could be the issue?
The code for my class is:
public class Overview extends Fragment implements AdapterView.OnItemClickListener {
private static final String DATA = "data";
public static final int ARTIST = 1;
public static final int ALBUM = 2;
public static final int PLAYLIST = 3;
int source;
RealmList<Track> trackList;
RealmList<Album> albumList;
#BindView(R.id.tracks)
ExpandableHeightListView tracks;
#BindView(R.id.albums)
RecyclerView albums;
#BindView(R.id.albumsLayout)
LinearLayout albumsLayout;
#OnItemClick(R.id.tracks)
void onItemSelected(int position){
Log.e("Tracks", String.valueOf(position));
}
#OnClick({R.id.all_tracks, R.id.all_albums})
public void showMore(View view) {
switch (view.getId()) {
case R.id.all_tracks:
break;
case R.id.all_albums:
break;
}
}
public Overview newInstance(Wrapper wrapper) {
Bundle bundle = new Bundle();
Overview overview = new Overview();
bundle.putParcelable(DATA, Parcels.wrap(wrapper));
overview.setArguments(bundle);
return overview;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.overview, container, false);
ButterKnife.bind(this, view);
tracks.setExpanded(true);
tracks.setOnItemClickListener(this);
albums.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
albums.setNestedScrollingEnabled(false);
Wrapper wrapper = Parcels.unwrap(getArguments().getParcelable(DATA));
trackList = wrapper.getTracks();
albumList = wrapper.getAlbums();
source = wrapper.getSource();
setItems(source);
return view;
}
private void setItems(int source) {
if (!trackList.isEmpty()) {
TrackListAdapter trackListAdapter;
switch (source) {
case ARTIST:
RealmList<Track> realmList = new RealmList<>();
ArrayList<Track> list = new ArrayList<>(trackList.size() > 10 ?
trackList.subList(0, 10) : trackList);
realmList.addAll(list);
trackListAdapter = new TrackListAdapter(getActivity(),
R.layout.track_list_item, realmList);
tracks.setAdapter(trackListAdapter);
break;
case PLAYLIST:
trackListAdapter = new TrackListAdapter(getActivity(),
R.layout.track_list_item, trackList);
tracks.setAdapter(trackListAdapter);
break;
case ALBUM:
trackListAdapter = new TrackListAdapter(getActivity(),
R.layout.album_track_list_item, trackList);
tracks.setAdapter(trackListAdapter);
break;
}
}
if (albumList != null && !albumList.isEmpty()) {
albumsLayout.setVisibility(View.VISIBLE);
AlbumsAdapter albumsAdapter = new AlbumsAdapter(getActivity(), albumList);
albums.setAdapter(albumsAdapter);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(Overview.class.getSimpleName(), String.valueOf(position));
}
}
It's layout file is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/DarkBodyBackground"
android:orientation="vertical">
<TextView
style="#style/DarkThemeHeaderText"
android:text="Top Tracks" />
<com.radioafrica.music.view.ExpandableHeightListView
android:id="#+id/tracks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/DarkCardBackgroundColor"
android:dividerHeight="1dip"
android:footerDividersEnabled="true"
android:headerDividersEnabled="true" />
<TextView
android:id="#+id/all_tracks"
style="#style/ShowAllText" />
<LinearLayout
android:id="#+id/albumsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:visibility="gone">
<TextView
style="#style/DarkThemeHeaderText"
android:text="Albums" />
<android.support.v7.widget.RecyclerView
android:id="#+id/albums"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/all_albums"
style="#style/ShowAllText" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>

Edittext automatically gets focus when move between pages in a view pager

I have an activity which hosts two fragments inside a view pager. I used the same layout to inflate those fragments. The layout has two edit texts placed inside a linear layout which is inside a relative layout. The problem is when I switch from fragment A to fragment B, he first edit text has focus in fragment A and when I return back from fragment B to fragment A, instead of the first edit text having focus, the second edit text gets the focus. How to solve it. I provide the layouts and source code below. I have not return any code inside the fragment classes.
Activity:
public class LoginActivity extends BaseActivity {
public static final String selectedTabPosition = "selectedTabPosition";
//Tab tag name
private static String TAB_1_TAG = "Email";
private static String TAB_2_TAG = "Mobile";
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TAB_1_TAG = getResources().getString(R.string.tab_email);
TAB_2_TAG = getResources().getString(R.string.tab_mobile);
//Initialise views
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
//set tab with view pager
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
setupTabIcons();
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
dismissKeyboard(mViewPager);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* Adding custom view to tab
*/
private void setupTabIcons() {
LinearLayout tabOne = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
TextView tvIconOne = (TextView) tabOne.findViewById(R.id.tv_tab_title);
tvIconOne.setText(TAB_1_TAG);
mTabLayout.getTabAt(0).setCustomView(tabOne);
setTypeface(tvIconOne, CustomFonts.Prime_regular);
mTabLayout.getTabAt(0).getCustomView().setSelected(true);
LinearLayout tabTwo = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
TextView tvIconTwo = (TextView) tabTwo.findViewById(R.id.tv_tab_title);
tvIconTwo.setText(TAB_2_TAG);
setTypeface(tvIconTwo, CustomFonts.Prime_regular);
mTabLayout.getTabAt(1).setCustomView(tabTwo);
}
/**
* Adding fragments to ViewPager
*
* #param viewPager The view pager
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
LoginFragment loginFragmentEmail = new LoginFragment();
Bundle emailBundle = new Bundle();
emailBundle.putInt(selectedTabPosition, 0);
loginFragmentEmail.setArguments(emailBundle);
LoginFragment loginFragmentMobile = new LoginFragment();
Bundle phoneBundle = new Bundle();
phoneBundle.putInt(selectedTabPosition, 1);
loginFragmentMobile.setArguments(phoneBundle);
adapter.addFrag(loginFragmentEmail, TAB_1_TAG);
adapter.addFrag(loginFragmentMobile, TAB_2_TAG);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment:
public class LoginFragment extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
activity_login.xml:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_title"
android:layout_width="200dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/custom_tab_layout_height"
android:layout_below="#+id/iv_title"
android:layout_marginTop="#dimen/spacing_10"
app:tabGravity="fill"
app:tabIndicatorColor="#color/app_color_dark"
app:tabMode="fixed"/>
<View
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="#dimen/divider_height_small"
android:layout_below="#+id/tabs"
android:background="#color/gray_medium"/>
<com.helper.CustomNonSwipeableViewpager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/view"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</RelativeLayout>
fragment_login.xml:
<?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:background="#android:color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/spacing_50"
android:orientation="vertical">
<EditText
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48"
/>
<EditText
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48"
android:layout_marginTop="#dimen/spacing_15"/>
</LinearLayout>
</RelativeLayout>
AndroidManifest.xml:
<activity
android:name=".activities.LoginActivity"
android:screenOrientation="portrait"
/>
In the AndrodManifest file, tried the
android:windowSoftInputMode = stateHidden and android:windowSoftInputMode = adjustPan
CustomNonSwipeableViewpager.java:
public class CustomNonSwipeableViewpager extends ViewPager {
public CustomNonSwipeableViewpager(Context context) {
super(context);
}
public CustomNonSwipeableViewpager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
}
ScreenShots:
Before moving to FragmentB:
In Fragment B:
Return back to Fragment A from Fragment B:
You can disable the focus on the EditText during runtime of the fragment:
EditText et_email_view = (EditText) rootView.findViewById(R.id.et_email);
et_email_view.setFocusable(false);
Use requestFocus attribute to your first editText which will always cause that editText to gain focus.
Make following changes in your fragment_login.xml file,
<EditText
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48">
<requestFocus />
</EditText>
For example in my case viewPager is covering editText. I set translationZ at editText(translationZ="2") and viewPage(translationZ="1") and it helped me.

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

Android: How to build Multiplelevel Tabs

I want to create multilevel tabs in android. It should follow a multilevel hierarchy, or a nested tabs philosophy as shown in image. Please provide the link or url if necessary.
Use Multiple Layers of Android TabLayout, Refer this. TabLayout is quite customize-able. For e.g. adding tabs, setting divider height, using custom views in tabs.
You should use ViewPager to do so. Below code will help you to make multilevel tabs in android.
view_pager_main.xml
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</FrameLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white" />
<TextView
android:id="#+id/tvNoPlans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Plans Available"
android:textColor="#android:color/black"
android:visibility="gone" />
</android.support.design.widget.AppBarLayout>
view_pager_child.xml
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout_child"
style="#style/MyCustomTabLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
app:tabIndicatorColor="#color/btn_background"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</FrameLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_child"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white" />
</android.support.design.widget.AppBarLayout>
ViewPagerMain.java
public class ViewPagerMain extends Fragment {
ViewPager viewpager;
TabLayout tabLayout;
TextView tvNoPlans;
View rootview;
Fragment fr = null;
ArrayList<String> cat_id = new ArrayList<String>();
ArrayList<String> cat_name = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.view_pager_main, container, false);
tvNoPlans = (TextView) rootview.findViewById(R.id.tvNoPlans);
viewpager = (ViewPager) rootview.findViewById(R.id.viewpager);
viewpager.setOffscreenPageLimit(3);
tabLayout = (TabLayout) rootview.findViewById(R.id.tabLayout);
cat_id.add(0,"1");
cat_id.add(1,"2");
cat_name.add(0,"Parent1");
cat_name.add(1,"Parent2");
setupViewpager(viewpager);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewpager);
}
});
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) {
}
});
return rootview;
}
public void setupViewpager(ViewPager viewPager) {
ViewpagerAdapter adapter = new ViewpagerAdapter(getChildFragmentManager());
for (int i = 0; i < cat_id.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("cat_id",cat_id.get(i));
fr = new ViewPagerChild();
fr.setArguments(bundle);
adapter.addFrag(fr, cat_name.get(i));
}
viewPager.setAdapter(adapter);
}
}
ViewPagerChild.java
public class ViewPagerChild extends Fragment {
ViewPager viewPager_child;
TabLayout tabLayout_child;
SharedPreferences preferences;
View rootview;
String cat_id;
ArrayList<String> subcat_id = new ArrayList<String>();
ArrayList<String> subcat_name = new ArrayList<String>();
Bundle bundle;
Fragment fr = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.view_pager_child, container, false);
preferences = getActivity().getSharedPreferences(Constant.PREF_MAIN, 0);
bundle = getArguments();
cat_id = bundle.getString("cat_id");
viewPager_child = (ViewPager) rootview.findViewById(R.id.viewpager_child);
viewPager_child.setOffscreenPageLimit(10);
tabLayout_child = (TabLayout) rootview.findViewById(R.id.tabLayout_child);
subcat_id.add(0,"1");
subcat_id.add(1, "2");
subcat_name.add(0,"Child1");
subcat_name.add(1,"Child2");
setupViewpagerChild(viewPager_child);
tabLayout_child.post(new Runnable() {
#Override
public void run() {
tabLayout_child.setupWithViewPager(viewPager_child);
}
});
tabLayout_child.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager_child.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootview;
}
public void setupViewpagerChild(ViewPager viewPager_child) {
ViewpagerAdapter adapter = new ViewpagerAdapter(getChildFragmentManager());
for (int i = 0; i < subcat_id.size(); i++) {
fr = new TabFragment();
adapter.addFrag(fr, subcat_name.get(i));
}
viewPager_child.setAdapter(adapter);
}
}
ViewpagerAdapter.java
public class ViewpagerAdapter extends FragmentPagerAdapter {
private final List<android.app.Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewpagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFrag(Fragment fragment,String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
tab_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="Hello There!!!"/>
</LinearLayout>
TabFragment.java
public class TabFragment extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_tab, container, false);
return rootview;
}
}

ViewPagers and PagerAdapters

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.

Categories

Resources