I have implemented the SwipeRefreshLayout in many of the pages,and it working fine. but here i got stuck with one specific implementation , where i have a SwipeRefreshLayout for the ViewPager and ViewPager holding the FragmentPagerAdapter.
In my case , I have a ViewPager with two tabs and each holding the fragment with RecyclerView. On main page I have a SwipeRefreshLayout and on the onRefresh i need to load the API and update the fragments in ViewPager. Updating is working fine but unfortunately RecyclerView inside the Fragment ( ViewPager tab Item ) not scrolling top and it always calling the SwipeToRefresh.
I am familiar with using the SwipeRefreshLayout with RecyclerView, but here the problem is the main child of the SwipeRefreshLayout is ViewPager and it having the Fragment inside it and that fragment is holding the RecyclerView.
I have a thought of moving the SwipeRefreshLayout inside the fragments for the RecyclerView , but again here i have challenges like both the Fragments is having the same API. So that i am using the SwipeRefreshLayout directly on ViewPager to refresh my data.
Here is some of my codes.
MainContacts.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">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll_process"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:alpha="1"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:indeterminate="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/fetching"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/contacts_screen"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/my_contacts_tabs"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
app:tabBackground="#color/colorWhite"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/my_contacts_view_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/transparent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
contacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hc="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/searchContainer"
android:animateLayoutChanges="true"
android:childDivider="#android:color/transparent" />
</RelativeLayout>
MainFragment ( Which i am using to load the child fragments , SwipeTORefreshLayout + ViewPager here)
public class MainFragment extends BaseFragment {
private TextView mTextError;
private LinearLayout llNoRecords, ll_process;
private ImageView iv_retry;
private MaterialSearchView materialSearchView;
PHCJsonResponseContactDetailModel mContactResponseModel;
int expandableListSelectionType = ExpandableListView.PACKED_POSITION_TYPE_NULL;
boolean actionModeEnabled;
private Activity mActivity;
SwipeRefreshLayout mSwipeRefreshLayout;
private ViewPager viewPager;
TabLayout tabLayout;
ContactsTabPagerAdapter mAdapter;
ArrayList<PHCContactDetailModel> mContactList =new ArrayList<>();
ArrayList<PHCContactDetailModel> mFavoriteList;
boolean isSwipeToRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActivity = getActivity();
View view = inflater.inflate(R.layout.phc_contact_fragment, container, false);
getViewId(view);
setListener();
if (isNetworkAvailable()) {
if(((MainDrawerActivity)mActivity).getPHCContactFragmentData()==null)
getAllContactData();
else
updateWidgets();
} else {
showNoNetworkToast();
llNoRecords.setVisibility(View.VISIBLE);
mTextError.setText(getResources().getText(R.string.no_internet_retry));
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onPrepareOptionsMenu(final Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.menu_fragment_group, menu);
}*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment_contacts, menu);
MenuItem item = menu.findItem(R.id.action_search);
materialSearchView.setMenuItem(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create_group) {
Intent createGroupIntent = new Intent(getActivity(), PHCCreateGroupActivity.class);
createGroupIntent.putExtra("comeFrom", PHCAppConstant.GROUP_ADD);
getActivity().startActivity(createGroupIntent);
}
return super.onOptionsItemSelected(item);
}
private void setListener() {
iv_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isNetworkAvailable()) {
getAllContactData();
} else {
showNoNetworkToast();
}
}
});
}
private void getViewId(View view) {
mTextError = (TextView) view.findViewById(R.id.textError);
ll_process = (LinearLayout) view.findViewById(R.id.ll_process);
llNoRecords = (LinearLayout) view.findViewById(R.id.ll_no_records);
iv_retry = (ImageView) view.findViewById(R.id.iv_retry);
viewPager = (ViewPager) view.findViewById(R.id.my_contacts_view_pager);
tabLayout = (TabLayout) view.findViewById(R.id.my_contacts_tabs);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(mContactResponseModel!=null && mContactResponseModel.getData().size() >0)
{
isSwipeToRefresh = true;
getAllContactData();
}
}
});
materialSearchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);
}
private void getAllContactData() {
if (isNetworkAvailable()) {
// showProgress();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCJsonResponseContactDetailModel> call = apiService.contactData(getApplicationData(getActivity()).getAuthToken(), getApplicationData(getActivity()).getUserID());
call.enqueue(new Callback<PHCJsonResponseContactDetailModel>() {
#Override
public void onResponse(Call<PHCJsonResponseContactDetailModel> call, Response<PHCJsonResponseContactDetailModel> response) {
Log.d(TAG, "getContacts URL " + response.raw().request().url());
Log.d(TAG, "getContacts Resp " + new Gson().toJson(response.body()));
mContactResponseModel = response.body();
((MainDrawerActivity)mActivity).setPHCContactFragmentData(mContactResponseModel);
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
if(isSwipeToRefresh)
{
isSwipeToRefresh=false;
updateWidgets();
}
else
updateWidgets();
}
#Override
public void onFailure(Call<PHCJsonResponseContactDetailModel> call, Throwable t) {
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
isSwipeToRefresh=false;
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
});
} else {
isSwipeToRefresh=false;
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
showNoNetworkAlert();
}
}
private void updateWidgets() {
if (mContactResponseModel.getStatusCode() == 401 || mContactResponseModel.getStatusCode() == 402) {
showSessionExpireAlert(mContactResponseModel.getStatusMessage(), mContactResponseModel.getStatusCode());
return;
}
if (mContactResponseModel != null && mContactResponseModel.getStatusCode() == 1) {
dismissProgress();
mTextError.setVisibility(View.GONE);
mContactList = mContactResponseModel.getData();
mFavoriteList = mContactResponseModel.getData();
if(mContactList!=null && mContactList.size()>0)
{
llNoRecords.setVisibility(View.GONE);
mAdapter = new ContactsTabPagerAdapter(getActivity().getApplicationContext(), getChildFragmentManager(), mContactList , mFavoriteList);
viewPager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(viewPager);
}
else {
llNoRecords.setVisibility(View.VISIBLE);
}
} else {
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
}
public void dismissProgress() {
ll_process.setVisibility(View.GONE);
super.dismissProgress();
}
private void initiateContactChat(final PHCFacilityDetailsModel facilityDetailsModel, final int groupPosition, final int childPosition) {
String header = getApplicationData(getActivity()).getAuthToken();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCContactInitiateChatResponseModel> call = apiService.initiateContactChat(header, facilityDetailsModel.getUserId(), getApplicationData(getActivity()).getUserID(), 0);
call.enqueue(new Callback<PHCContactInitiateChatResponseModel>() {
#Override
public void onResponse(Call<PHCContactInitiateChatResponseModel> call, Response<PHCContactInitiateChatResponseModel> response) {
Log.d(TAG, "initiateContactChat URL " + response.raw().request().url());
Log.d(TAG, "initiateContactChat Resp " + new Gson().toJson(response.body()));
PHCContactInitiateChatResponseModel mContactInitiateChatModel = response.body();
if (mContactInitiateChatModel != null && mContactInitiateChatModel.getStatusCode() == 1) {
Intent chatIntent = new Intent(getActivity(), PHCChatActivity.class);
// chatIntent.putExtra("headerName",mData.get(groupPosition).getFacilityDetails().get(childPosition).getUserName());
chatIntent.putExtra("headerName", facilityDetailsModel.getUserName());
chatIntent.putExtra("groupId", mContactInitiateChatModel.getData().getGroupId());
getActivity().startActivity(chatIntent);
}
}
#Override
public void onFailure(Call<PHCContactInitiateChatResponseModel> call, Throwable t) {
Toast.makeText(getActivity(), "Something went wrong! Please try again", Toast.LENGTH_SHORT).show();
}
});
}
}
ContactsTabPagerAdapter.java
public class ContactsTabPagerAdapter extends FragmentPagerAdapter {
/**
* The Page count.
*/
final int PAGE_COUNT = 2;
private String[] tabTitles = { "Contacts", "Favorites" };
private ArrayList<PHCContactDetailModel> mContactsList;
private ArrayList<PHCContactDetailModel> mFavoritesList;
Context mContext ;
public ContactsTabPagerAdapter(Context context, FragmentManager fm ,ArrayList<PHCContactDetailModel> contacts , ArrayList<PHCContactDetailModel> favs) {
super(fm);
this.mContext = context;
this.mContactsList = contacts;
this.mFavoritesList=favs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
ContactsFragment mContactsFragment =new ContactsFragment();
Bundle bundle=new Bundle();
bundle.putSerializable("Contacts", (Serializable) mContactsList);
mContactsFragment.setArguments(bundle);
return mContactsFragment;
case 1:
FavoritesFragment mFavoritesFragment=new FavoritesFragment();
Bundle pastBundle=new Bundle();
pastBundle.putSerializable("Favorites", (Serializable) mFavoritesList);
mFavoritesFragment.setArguments(pastBundle);
return mFavoritesFragment;
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
/**
* Update.
*
* #param lContactsList contact list to update
* #param lFavoritesList favorites list to update
*/
//call this method to update fragments in ViewPager dynamically
public void update(ArrayList<PHCContactDetailModel> lContactsList, ArrayList<PHCContactDetailModel> lFavoritesList) {
this.mContactsList = lContactsList;
this.mFavoritesList = lFavoritesList;
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
if (object instanceof UpdatableFragment) {
((UpdatableFragment) object).update(mContactsList, mFavoritesList);
}
//don't return POSITION_NONE, avoid fragment recreation.
return super.getItemPosition(object);
}
}
ContactsFragment.java
public class ContactsFragment extends BaseFragment implements UpdatableFragment{
private static final String TAG = "ContactFragmentTab";
private FloatingGroupExpandableListView mContactExpandableList;
private PHCContactAdapter mAdapter;
WrapperExpandableListAdapter wrapperAdapter;
boolean actionModeEnabled;
private LinearLayout llNoRecords;
private ArrayList<PHCContactDetailModel> mContactsData;
public ContactsFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
getViewId(rootView);
Bundle bundle= getArguments();
if(bundle !=null)
{
Log.d(TAG, "bundle is not empty");
mContactsData= (ArrayList<PHCContactDetailModel>) bundle.getSerializable("Contacts");
}
System.out.print("Contacts Size::" + mContactsData.size());
if(mContactsData!=null)
{
updateWidgets();
}
return rootView;
}
private void updateWidgets() {
mAdapter = new PHCContactAdapter(getActivity(), mContactsData, new ListShowingHidingListener() {
#Override
public void listHideAndShow(boolean isData) {
if (isData) {
llNoRecords.setVisibility(View.GONE);
mContactExpandableList.setVisibility(View.VISIBLE);
listUpdate();
} else {
llNoRecords.setVisibility(View.VISIBLE);
mContactExpandableList.setVisibility(View.GONE);
}
}
});
wrapperAdapter = new WrapperExpandableListAdapter(mAdapter);
mContactExpandableList.setAdapter(wrapperAdapter);
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void listUpdate() {
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void getViewId(View view) {
// mContactExpandableList = (ExpandableListView) view.findViewById(R.id.contactList);
mContactExpandableList = (FloatingGroupExpandableListView) view.findViewById(R.id.contactList);
}
#Override
public void update(ArrayList<PHCContactDetailModel> contactsData, ArrayList<PHCContactDetailModel> favoritesData) {
this.mContactsData = contactsData;
updateWidgets();
}
}
similarly i have Favorites example as well. Mostly both will look like same, that's why not posting it here.
Sorry for posting the long question. Any help regarding this. Apologies for my poor English. Thanks in Advance.
Related
I want to place FrameView over Toolbar as show in the image below -
You can see that the RecyclerView in the FrameView is overlapping Toolbar
But I'm getting this instead as show in the image below -
In the Android Studio preview its showing correctly which means frame layout is over the toolbar like this -
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/dim_50">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ImageButton
android:id="#+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_navigate_before_black_24dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:id="#+id/topicLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quiz"
android:textColor="#android:color/white"
android:textSize="#dimen/dim_19"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:background="#android:color/transparent">
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements BaseFragment.OnBaseFragListener {
Toolbar toolbar;
TextView txtLabel;
ImageButton backButton;
ImageView topicLogo;
int navHomeVisibility = 1;
int navAboutVisibility = 1;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
ViewGroup.MarginLayoutParams labelParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
txtLabel = findViewById(R.id.txtLabel);
backButton = findViewById(R.id.backButton);
topicLogo = findViewById(R.id.topicLogo);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
sharedPreferences = getSharedPreferences("preferences", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.apply();
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
AddFrag(new ChooseTopicFragment(), 0, null);
labelParams = (ViewGroup.MarginLayoutParams) txtLabel.getLayoutParams();
}
public void setTitleMargin() {
labelParams.setMargins((int) getResources().getDimension(R.dimen.dim_10), 0, 0, 0);
}
public void unsetTitleMargin() {
labelParams.setMargins(0, 0, 0, (int) getResources().getDimension(R.dimen.dim_1));
}
public void setFragTitle(String FragTitle) {
txtLabel.setText(FragTitle);
}
public void setFragLogo(int FragLogo) {
topicLogo.setVisibility(View.VISIBLE);
topicLogo.setImageResource(FragLogo);
}
public void unsetFragLogo() {
topicLogo.setVisibility(View.GONE);
}
public void unsetMenuItems(int navHomeFlag) {
navHomeVisibility = navHomeFlag;
invalidateOptionsMenu();
backButton.setVisibility(View.GONE);
txtLabel.setTextSize(20);
}
public void setMenuItems(int navHomeFlag) {
navHomeVisibility = navHomeFlag;
invalidateOptionsMenu();
backButton.setVisibility(View.VISIBLE);
txtLabel.setTextSize(19);
}
public void unsetAbout(int navAboutFlag) {
navAboutVisibility = navAboutFlag;
invalidateOptionsMenu();
}
public void setAbout(int navAboutFlag) {
navAboutVisibility = navAboutFlag;
invalidateOptionsMenu();
}
public void unsetOnlyBackBtn() {
backButton.setVisibility(View.INVISIBLE);
}
public void AddFrag(Fragment fragment, int flag, String fragName) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (flag == 0) {
ft.add(R.id.container, fragment, fragName); //for adding ChooseTopic frag
} else if (flag == 1) {
ft.replace(R.id.container, fragment, fragName);
ft.addToBackStack(fragName);
} else if (flag == 2) {
ft.replace(R.id.container, fragment, fragName); //skips adding Questions frag to backstack
} else if (flag == 3) {
ft.remove(fragment); //removes Result frag after pressing back
}
ft.commitAllowingStateLoss();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem navHome = menu.findItem(R.id.navHome);
if (navHomeVisibility == 0)
navHome.setVisible(false);
else
navHome.setVisible(true);
MenuItem navAbout = menu.findItem(R.id.navAbout);
if (navAboutVisibility == 0)
navAbout.setVisible(false);
else
navAbout.setVisible(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.navHome) {
finishAffinity();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else if (item.getItemId() == R.id.navAbout) {
AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
aboutDialog.setTitle("About");
aboutDialog.setMessage(getResources().getText(R.string.about_desc));
aboutDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
aboutDialog.show();
}
return true;
}
#Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof BaseFragment) {
BaseFragment baseFragment = (BaseFragment) fragment;
baseFragment.setOnBaseFragListener(this);
}
}
}
ChooseTopicFragment
public class ChooseTopicFragment extends BaseFragment {
private ArrayList<TopicModal> arrTopicModal = new ArrayList<>();
public ChooseTopicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_choose_topic, container, false);
arrTopicModal.clear();
callback.unsetMenuItems(0);
callback.setAbout(1);
callback.unsetFragLogo();
callback.setFragTitle("Programming Quiz");
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
DBHelper dbHelper = DBHelper.getDB(getActivity());
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
ArrayList<Integer> arrBeg = new ArrayList<>();
ArrayList<Integer> arrInt = new ArrayList<>();
ArrayList<Integer> arrExp = new ArrayList<>();
for (int i = 1; i < 11; i++) {
arrBeg.add(dbHelper.getCount("Beginner", i));
arrInt.add(dbHelper.getCount("Intermediate", i));
arrExp.add(dbHelper.getCount("Expert", i));
}
addTopics(1, R.drawable.ic_java, "Java", arrBeg.get(0), arrInt.get(0), arrExp.get(0), getResources().getColor(android.R.color.holo_blue_dark));
addTopics(2, R.drawable.ic_c, "C", arrBeg.get(1), arrInt.get(1), arrExp.get(1), getResources().getColor(android.R.color.holo_red_light));
addTopics(3, R.drawable.ic_cpp, "C++", arrBeg.get(2), arrInt.get(2), arrExp.get(2), getResources().getColor(android.R.color.holo_orange_light));
addTopics(4, R.drawable.ic_android, "Android", arrBeg.get(3), arrInt.get(3), arrExp.get(3), getResources().getColor(android.R.color.holo_green_dark));
addTopics(5, R.drawable.ic_php, "PHP", arrBeg.get(4), arrInt.get(4), arrExp.get(4), getResources().getColor(android.R.color.holo_orange_dark));
addTopics(6, R.drawable.ic_css, "CSS", arrBeg.get(5), arrInt.get(5), arrExp.get(5), getResources().getColor(android.R.color.holo_purple));
addTopics(7, R.drawable.ic_html, "HTML", arrBeg.get(6), arrInt.get(6), arrExp.get(6), getResources().getColor(android.R.color.holo_orange_light));
addTopics(8, R.drawable.ic_python, "Python", arrBeg.get(7), arrInt.get(7), arrExp.get(7), getResources().getColor(android.R.color.holo_blue_dark));
addTopics(9, R.drawable.ic_javascript, "Javascript", arrBeg.get(8), arrInt.get(8), arrExp.get(8), getResources().getColor(android.R.color.holo_red_light));
addTopics(10, R.drawable.ic_kotlin, "Kotlin", arrBeg.get(9), arrInt.get(9), arrExp.get(9), getResources().getColor(android.R.color.holo_green_dark));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
TopicAdapter adapter = new TopicAdapter(getActivity(), arrTopicModal);
recyclerView.setAdapter(adapter);
return view;
}
public void addTopics(int topicID, int image, String name, int beginner, int intermediate, int expert, int topicColor) {
TopicModal topicModal = new TopicModal();
topicModal.topicID = topicID;
topicModal.image = image;
topicModal.name = name;
topicModal.beginner = beginner;
topicModal.intermediate = intermediate;
topicModal.expert = expert;
topicModal.topicColor = topicColor;
arrTopicModal.add(topicModal);
}
}
It's not the most elegant way but you could set the elevation on the different views to force which is on top. Also I believe within a frame layout the order in which you add the layout in your xml plays an important role in what is causing your problems
I have 3 DialogFragments A, B and C. I am starting Fragment A from Activity using FragmentTransaction Like this:
FragmentA dialog = new FragmentA();
Bundle bundle = new Bundle();
bundle.putString("GameLevelType", "Puzzle");
dialog.setArguments(bundle);
FragmentTransaction transaction = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(android.R.id.content, dialog).addToBackStack(null).commit();
Now I am starting Fragment B from inside the Adapter of the RecyclerView of Fragment A Like this:
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView levelName;
CardView gameCard;
public MyViewHolder(View itemView) {
super(itemView);
levelName = (TextView) itemView.findViewById(R.id.gameText);
gameCard = (CardView) itemView.findViewById(R.id.gameCard);
gameCard.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
FragmentB fragment = new FragmentB();
FragmentTransaction gameTransaction = ((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
gameTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
gameTransaction.add(android.R.id.content, fragment).addToBackStack(null).commit();
//fragment.show(((AppCompatActivity)context).getSupportFragmentManager(),"PuzzleDialog");
}
});
//((AppCompatActivity) context).getSupportFragmentManager().popBackStack();
}
}
Now I am starting Fragment C from Fragment B. But the Fragment C is not visible.
Here is Fragment C:
public class FragmentC extends DialogFragment implements OnStartDragListener {
private ItemTouchHelper mItemTouchHelper;
RecyclerView recyclerView;
Integer[] str = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9};
List<Integer> itemList = new ArrayList<>(Arrays.asList(str));
List<Integer> actualList = new ArrayList<>(Arrays.asList(str));
RelativeLayout layout;
PuzzleGridAdapter adapter;
Toolbar toolbar;
public PuzzleGameFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.puzzle_game_dialog, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
toolbar.setTitle(R.string.puzzle);
//toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel);
}
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
layout = (RelativeLayout) view.findViewById(R.id.puzzleLayout);
recyclerView = (RecyclerView) view.findViewById(R.id.gridItems);
adapter = new PuzzleGridAdapter(getActivity(), this);
recyclerView.setHasFixedSize(true);
Collections.shuffle(itemList);
adapter.getItemList(itemList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.setItemAnimator(new DefaultItemAnimator() {
#Override
public void onAnimationFinished(RecyclerView.ViewHolder viewHolder) {
for (Integer s : adapter.getUpdateList()) {
Log.e("Final List", s + "");
}
int j = 0;
for (int i = 0; i < adapter.getUpdateList().size(); i++) {
Log.e("ItemList", itemList.get(i) + " ");
if (adapter.getUpdateList().get(i).equals(actualList.get(i))) {
j++;
}
}
if (j == adapter.getUpdateList().size()) {
Log.e("Solved", "True");
}
}
});
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
#Override
public void onResume() {
super.onResume();
Calendar globalCalendar = Calendar.getInstance();
int timeOfDay = globalCalendar.get(Calendar.HOUR_OF_DAY);
if (timeOfDay >= 0 && timeOfDay < 12) {
layout.setBackground(getResources().getDrawable(R.drawable.gradient_morning_background));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryMorning));
} else {
layout.setBackground(getResources().getDrawable(R.drawable.gradient_background));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// handle close button click here
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().popBackStack();
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is fragment_c.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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:clickable="true"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/puzzleLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/toolbarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbarLayout">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:adjustViewBounds="true"
android:alpha="0.5"
android:scaleType="fitXY"
android:src="#drawable/background_img" />
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:adjustViewBounds="true"
android:alpha="0.5"
android:rotation="180"
android:scaleType="fitXY"
android:src="#drawable/background_img" />
<android.support.v7.widget.RecyclerView
android:id="#+id/gridItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="25dp" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Why the Fragment C is not visible ?
i've had a problem, when i've tried to view this below fragment showing "skipping layout". Can any one help me out how to solve this problem please.
I'm getting this "No adapter attached; skipping layout." when i CLICK any imageview on ThirdFragment UI ayout, not when the images display in Thirdfragment UI layout.
ThirdFrament.java
public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {
static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
AutoFitGridLayoutManager layoutManager;
private static List<JsonURLFullModel> cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
new JSONTask().execute(url, this);
// Inflate the layout for this fragment
return rootView;
}
public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
// Url , , return_value_of_doInBackground
//private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.show(); // this is for ProgressDialog
}
#Override
protected ThirdFragModel doInBackground(Object... params) {
//send and receive data over the web
// can be used to send and receive "streaming" data whose length is not
// known in advance
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0].toString());
RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream(); // this is used to store
// the response, response is always stream
reader = new BufferedReader(new InputStreamReader(stream));
// BufferedReader reads the stream line by line and then store in the reader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString(); // this contails whole JSON data from the URL
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL
List<JsonURLFullModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferedaData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
JsonURLFullModel movieModel = new JsonURLFullModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setImage(finalObject.getString("image"));
movieModelList.add(movieModel); // adding the final object in list
//finalBufferedaData.append(movieName +"-"+ year +"\n");
}
ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);
return thirdFragModel;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());
/**
AutoFitGridLayoutManager that auto fits the cells by the column width defined.
**/
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
/**
Simple GridLayoutManager that spans two columns
**/
/*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);*/
//AnimationUtils.animate(jsonFullL1, true);
}
}
public void moveToLoginActivity() {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
#Override
public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {
Log.d("Fragposition",mPosition+":"+mValues);
Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
intent.putExtra("position", mPosition);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
public static List<JsonURLFullModel> getCart() {
if(cart == null) {
cart = new Vector<JsonURLFullModel>();
}
return cart;
}
}
Here is my adapter class which we used in ThirdFragment class as shown above
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static List<JsonURLFullModel> mValues;
Context mContext;
private ItemListener mListener;
static int mPosition;
public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {
mValues = values;
mContext = context;
mListener=itemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ImageView imageView;
public RelativeLayout relativeLayout;
JsonURLFullModel item;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
textView = (TextView) v.findViewById(R.id.textView1);
imageView = (ImageView) v.findViewById(R.id.imageView1);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
}
public void setData(final JsonURLFullModel item) {
this.item = item;
Log.d("INFO",item.getImage());
//https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit
Picasso.with(mContext)
.load(item.getImage())
.error(R.drawable.ferrari)
.noPlaceholder()
.noFade()
.fit()
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Success image already loaded into the view
Log.d("INFO","success");
}
#Override
public void onError() {
//Error placeholder image already loaded into the view, do further handling of this situation here
Log.d("INFO","error");
}
});
/*imageView.post(new Runnable() {
#Override
public void run(){
Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);
}
});*/
textView.setText(item.getMovie());
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
// in API 22 and we got getAdapterPosition()
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
Vholder.setData(mValues.get(position));
mPosition=position;
}
#Override
public int getItemCount() {
return mValues.size();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
}
FullScreenViewInitialActivity.java
public class FullScreenViewInitialActivity extends FragmentActivity {
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
static ArrayList<JsonURLFullModel> mValues;
static int position;
Button addToBagButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view_initial);
addToBagButton = (Button) findViewById(R.id.b_add_to_bag);
Intent i = getIntent();
position=i.getIntExtra("position",0);
Log.d("Acposition",""+position);
mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.intial_pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
circleIndicator.setViewPager(viewPager);
/*viewPager.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
intent.putExtra("position", position);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
});*/
final List<JsonURLFullModel> cart = ThirdFragment.getCart();
final JsonURLFullModel selectedProduct = mValues.get(position);
addToBagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart.add(selectedProduct);
Log.d("cart",""+cart.size());
//finish();
Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
b_add_to_bag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
startActivity(reviewOrderIntent);
}
});
}
});
if(cart.contains(selectedProduct)) {
addToBagButton.setEnabled(false);
addToBagButton.setText("Item in Cart");
}
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
/*Bundle bundle = getArguments();
int position = bundle.getInt("position");*/
//JsonURLFullModel imageFileName = mValues.get(position);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
/*options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
URL url = new URL(mValues.get(position).getImage());
Log.d("position",""+position);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
System.out.println("The Bitmap is NULL");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
}
});
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
third_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
<!--removed from recycler view
app:layout_behavior="#string/appbar_scrolling_view_behavior"-->
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
card_view:cardCornerRadius="#dimen/margin10"
card_view:cardElevation="#dimen/margin10"
card_view:cardMaxElevation="#dimen/margin10"
card_view:contentPadding="#dimen/margin10"
card_view:cardPreventCornerOverlap="false"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:layout_marginTop="10dp"
android:layout_below="#+id/imageView1" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_fullscreen_view_initial
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/cart_button_layout"
android:layout_alignParentTop="true"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/intial_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/imageIndicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignBottom="#+id/intial_pager"
android:layout_marginBottom="10dp" />
</LinearLayout>
</ScrollView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/full_screen_size_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cart_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/b_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#D3D3D3"
android:text="save"
android:textColor="#000000" />
<Button
android:id="#+id/b_add_to_bag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:text="add to bag"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
swipe_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
Try setting the setting the RecyclerView with an empty Adapter before you execute your AsyncTask.
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
new JSONTask().execute(url, this);
Then create a method in the RecyclerViewAapter to load the the populated List<JsonURLFullModel> from the AsyncTask's onPostExecute.
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
If that doesn't work trying loading on the Ui thread from Asynctask using runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(...)
}
});
Edit 1 Adding loadJson to your RecyclerViewAapter.class
#Override
public int getItemCount() {
return mValues.size();
}
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
Call the method in your PostExecute
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(result.getMovieModelList());
}
});
}
Also add your the Layout manager for the RecyclerView in onCreateView
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
I'm using 1 Activity and 4 TabFragment in Android. When I add a keylistener in second TabFragment using EditText , My first TabFragment opens keyboard. I controlled that 2 xml_layout different each other.
So any idea why Fragments affect each other and how to prevent this ? . Did you anyone face that problem ?
tab_fragment_detailcomment.xml
<?xml version="1.0" encoding="utf-8"?>
``<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/profile_picture"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="15dp"/>
<TextView
android:id="#+id/name_surname"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="80dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="80dp">
<ImageView
android:id="#+id/starIcon"
android:layout_width="20dp"
android:layout_height="20dp" />
<TextView
android:id="#+id/starCount"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginStart="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginStart="80dp">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="40dp"
android:background="#drawable/comment_box"
android:hint="Add Commment"
android:paddingLeft="10dp"
android:inputType="textVisiblePassword">
<requestFocus />
</EditText>
</LinearLayout>
TabFragment_DetailComment.java
public class TabFragment_DetailComment extends Fragment {
#BindView(R.id.profile_picture)
ImageView profile_picture;
#BindView(R.id.name_surname)
TextView name_surname;
#BindView(R.id.comment)
TextView comment;
#BindView(R.id.starIcon)
ImageView starIcon;
#BindView(R.id.starCount)
TextView starCount;
#BindView(R.id.editText)
EditText editText;
int feedId;
List<FeedComment> feedComment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, `
`Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.tab_fragment_detailcomment, container, false);
ButterKnife.bind(this,view);
feedId = ((FeedDetailActivity) getActivity()).getFeedId();
addKeyListener();
ServiceController service = new ServiceController();
Call<ResponseFeedComment> call = service.getFeedServiceCallInterface().getFeedComment(feedId);
call.enqueue(new Callback<ResponseFeedComment>() {
#Override
public void onResponse(Call<ResponseFeedComment> call, Response<ResponseFeedComment> response) {
if (response != null) {
feedComment = response.body().getData();
profile_picture.setImageResource(R.drawable.male);
for(int i=0; i < feedComment.size(); i++) {
name_surname.setText(feedComment.get(i).getDisplayToken());
comment.setText(feedComment.get(i).getBody());
starIcon.setImageResource(R.drawable.star);
starCount.setText(feedComment.get(i).getLikeCount().toString());
}
}else {
Log.v("Response", "NULL");
}
}
#Override
public void onFailure(Call<ResponseFeedComment> call, Throwable t) {
}
});
return view;
}
public void addKeyListener() {
// add a keylistener to keep track user input
editText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// if keydown and "enter" is pressed
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
// display a floating message
Toast.makeText(getContext(),
editText.getText(), Toast.LENGTH_LONG).show();
return true;
} else if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_9)) {
// display a floating message
Toast.makeText(getContext(),
"Number 9 is pressed!", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
});
}
}
FeedDetailActivity.java
public class FeedDetailActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
String nameSurname;
int feedId;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
// toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nameSurname = getIntent().getStringExtra("nameSurname");
Intent i = getIntent();
feedId = i.getIntExtra("feedId",0); // 20 for default value
// feedId = getIntent().getStringExtra("feedId"); // Hata burda
viewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
public String getNameSurname() {
return nameSurname;
}
public int getFeedId() {
return feedId;
}
private void setupViewPager(ViewPager viewPager) {
FeedDetailActivity.ViewPagerAdapter adapter = new FeedDetailActivity.ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabFragment_DetailFeed(), "DETAIL");
adapter.addFragment(new TabFragment_DetailComment(), "COMMENT");
adapter.addFragment(new TabFragment_DetailImage(), "IMAGE");
adapter.addFragment(new TabFragment_DetailSurvey(), "SURVEY");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Try this
Set android:clickable="true"and also set background to parent layout of each fragment xml.
I have Fragment which have a searchview and viewpager . My viewpager has 3 fragments and each fragment calling adapter . Now to implement searchview , i need to call adapter of visible fragment in view pager .
SlidingTab(Fragment with searchview and ViewPager):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.RareMediaCompany.BDTrial.SlidingTab">
<include
android:id="#+id/toolbar1"
layout="#layout/toolbar_job" />
<com.RareMediaCompany.BDTrial.Utils.CustomTabLayout
android:id="#+id/sliding_tabs"
style="#style/CustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
app:tabIndicatorColor="#f39220"
app:tabIndicatorHeight="3dp"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabPaddingEnd="0dp"
app:tabPaddingStart="0dp"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabSelectedTextColor="#808080" />
<LinearLayout
android:id="#+id/linear1"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:weightSum="1">
<android.support.v7.widget.SearchView
android:layout_width="300dp"
android:layout_height="45dp"
android:id="#+id/searchView"
android:layout_weight="0.9"
android:layout_marginRight="5dp"
android:layout_gravity="center"
style="#style/CitySearchView"
android:background="#drawable/searchview"
android:layout_marginLeft="10dp"/>
<LinearLayout
android:id="#+id/list_linearlayout"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_weight="0"
android:layout_gravity="center"
android:background="#f39220">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0.3"
android:src="#drawable/list_icon_white"/>
</LinearLayout>
<LinearLayout
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_weight="0"
android:layout_marginRight="10dp"
android:background="#75aadb">
<ImageView
android:layout_width="20dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="2dp"
android:layout_weight="0.3"
android:src="#drawable/mapmarker"/>
</LinearLayout>
</LinearLayout>
<!--android:layout_width="320dp"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_marginLeft="10dp"-->
<!--android:layout_marginTop="10dp"-->
<!--android:id="#+id/searchview"/>-->
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
SlidingTab.class (Implementing SearchView)
public class SlidingTab extends Fragment {
private static final String TAG = "TabLayout";
private static String POSITION = "POSITION";
private Context context;
private SearchView searchview;
private Toolbar toolbar ;
/*searching/filteration query*/
private SearchView.OnQueryTextListener OnQuerySearchView = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
// if (searchCheck) {
Log.i("Recycler query", arg0);
// Fragment frag = new PageAdapter(getChildFragmentManager(),context).getItem(viewPager.getCurrentItem());
PageAdapter adapter = ((PageAdapter) viewPager.getAdapter());
Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());
return false;
}
};
public SlidingTab() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sliding_tab, container, false);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new PageAdapter(getChildFragmentManager(), context));
slidingTab = (TabLayout) v.findViewById(R.id.sliding_tabs);
searchview = (SearchView)v.findViewById(R.id.searchView);
searchview.setOnQueryTextListener(OnQuerySearchView);
return v;
}
PageAdapter.class
public class PageAdapter extends FragmentStatePagerAdapter {
private static final String TAG = "PageAdapter";
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"New", "In Progress", "Completed"};
private Context context;
public PageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
Log.d(TAG, "New Instance Created :" + position);
switch (position) {
case 0:
return new JobFragment();
case 1:
return new InProgressJobFragment();
case 2:
return new CompletedJobFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
Fragment RecyclerView Adapter (Call by each fragment in view pager and have searchview filter method)
public class JobAdapter extends RecyclerView.Adapter<JobAdapter.ViewHolder> {
private static final String TAG = "EMPLOYEE ADAPTER";
private static final int VIEW_NORMAL = 0;
private ArrayList<Info> mDataset;
private ArrayList<Info> filterList;
private Context mAct;
public class ViewHolder extends RecyclerView.ViewHolder {
}
}
public void addApplications(ArrayList<Info> candidates) {
}
public void clearApplications() {
}
public JobAdapter(ArrayList<Info> myDataset, Context context) {
this.mDataset = myDataset;
this.mAct = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.job_card_new, parent, false);
ViewHolder fh = new ViewHolder(v);
return fh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// }
**// *searching/filtration on List*/**
public void filter(String charText) {
filterList.clear();
if (charText.length() == 0) {
if(mDataset != null) {
filterList.addAll(mDataset);
}
} else {
if (mDataset != null){
for (Info wp : mDataset) {
if(wp.jobNumber !=null){
if(Pattern.compile(Pattern.quote(charText), Pattern.CASE_INSENSITIVE).matcher(wp.jobNumber).find()){
// if (wp.heading1.toLowerCase().contains(charText.toLowerCase())) {
filterList.add(wp);
}}else{
}
this.notifyItemRangeRemoved(0, filterList.size());
}
}
}
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
Please help me in implementing searchview in viewpager .
With help of uploaded code
I can tell that
make method in your fragments named search and
call adapter filter method
public void search(String text)
{
adapter.filter(text)
}
you can check instance of fragment and call search method of fragment after this line
Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());
I think the best design for this is to use the Activity as the central "hub" for events that need to go the fragments.
So this is how I would do this:
First start with a listener interface. This can be declared as an inner interface of the Activity:
static interface QueryListener {
void onQueryChange(String query);
}
Activity gets properties for holding listeners and methods for adding and removing listeners (declared synchronized to prevent those pesky ConcurrentModificationExceptions:
private List<QueryListener> mQueryListeners = new ArrayList<>();
public synchronized void addQueryListener(#NonNull QueryListener listener) {
// check if the listener was already added
// you could also use a Set instead of a List for this
if (mQueryListeners.contains(listener)) return;
mQueryListeners.add(listener);
}
public synchronized void removeQueryListener(#NonNull QueryListener listener) {
mQueryListeners.remove(listener);
}
Activity also gets a method that can be called by the fragment with the SearchView:
public synchronized void changeQuery(String query) {
for (QueryListener listener : mQueryListeners) {
listener.onQueryChange(query);
}
}
Now your fragments with the adapters need to implement QueryListener and register/unregister themselves:
Add this line somewhere in onCreate():
((YourActivity) getActivity()).addQueryListener(this);
Unregister in onDestroy():
#Override
public void onDestroy() {
((YourActivity) getActivity()).removeQueryListener(this);
super.onDestroy();
}
add the QueryListener method implementation:
#Override
public void onQueryChange(String query) {
// if (isVisible()) { if desired
mAdapter.filter(query);
}
Note: You don't have to have the fragment implement QueryListener; you can use an anonymous class. But you'll have to hold the reference to it so you can call removeQueryListener() with it later.
Now just hook up the SearchView:
#Override
public boolean onQueryTextChange(String query) {
((YourActivity) getActivity()).changeQuery(query);
}
Another pattern I've used is to create a dedicated class for registering/notifying listeners. I create a single instance of this class and have a method on the Activity to access it:
QueryHandler handler = ((YourActivity) getActivity()).getQueryHandler();
// QueryHandler has all the listener properties and methods shown for the Activity
...
handler.changeQuery(query);
Alternatively, you can also use one of the many open-source event bus packages like Otto to pass events amongst your fragments.