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
Related
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.
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'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 am using Android-ObservableScrollView
in my project.
I am facing a problem as, even if I just touch the viewpager the SlidingTab catches this event and the Current fragment of the view pager gets changed. I am pasting all the code from my project, but most of the code is similar to the sample project.
I investigated this issue online and find this issue useful, but i tried this solution but it did not work for me.
Please help.
THIS IS THE ISSUE
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
refreshJobsData = true;
setUpViewPager();
}
public void setUpViewPager() {
mHeaderView = findViewById(R.id.header);
ViewCompat.setElevation(mHeaderView, getResources().getDimension(R.dimen.toolbar_elevation));
mToolbarView = findViewById(R.id.toolbar);
mPagerAdapter = new NavigationAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mPagerAdapter);
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
slidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
slidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.theme_green_dark));
slidingTabLayout.setDistributeEvenly(false);
slidingTabLayout.setViewPager(mPager);
// When the page is selected, other fragments' scrollY should be adjusted
// according to the toolbar status(shown/hidden)
slidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
propagateToolbarState(toolbarIsShown());
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
propagateToolbarState(toolbarIsShown());
}
#Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (dragging) {
int toolbarHeight = mToolbarView.getHeight();
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (firstScroll) {
if (-toolbarHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mBaseTranslationY = 0;
Fragment fragment = getCurrentFragment();
if (fragment == null) {
return;
}
View view = fragment.getView();
if (view == null) {
return;
}
int toolbarHeight = mToolbarView.getHeight();
final ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
if (listView == null) {
return;
}
int scrollY = listView.getCurrentScrollY();
if (scrollState == ScrollState.DOWN) {
showToolbar();
} else if (scrollState == ScrollState.UP) {
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else {
// Even if onScrollChanged occurs without scrollY changing, toolbar should be adjusted
if (toolbarIsShown() || toolbarIsHidden()) {
// Toolbar is completely moved, so just keep its state
// and propagate it to other pages
propagateToolbarState(toolbarIsShown());
} else {
// Toolbar is moving but doesn't know which to move:
// you can change this to hideToolbar()
showToolbar();
}
}
}
private Fragment getCurrentFragment() {
return mPagerAdapter.getItemAt(mPager.getCurrentItem());
}
private void propagateToolbarState(boolean isShown) {
int toolbarHeight = mToolbarView.getHeight();
// Set scrollY for the fragments that are not created yet
mPagerAdapter.setScrollY(isShown ? 0 : toolbarHeight);
// Set scrollY for the active fragments
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
// Skip current item
if (i == mPager.getCurrentItem()) {
continue;
}
// Skip destroyed or not created item
Fragment f = mPagerAdapter.getItemAt(i);
if (f == null) {
continue;
}
ObservableListView listView = (ObservableListView) f.getView().findViewById(R.id.scroll);
if (isShown) {
// Scroll up
if (0 < listView.getCurrentScrollY()) {
listView.setSelection(0);
}
} else {
// Scroll down (to hide padding)
if (listView.getCurrentScrollY() < toolbarHeight) {
listView.setSelection(1);
}
}
}
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(mHeaderView) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(mHeaderView) == -mToolbarView.getHeight();
}
private void showToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
propagateToolbarState(true);
}
private void hideToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mToolbarView.getHeight();
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
propagateToolbarState(false);
}
private static class NavigationAdapter extends CacheFragmentStatePagerAdapter {
private static final String[] TITLES = new String[]{"Applepie", "Butter Cookie", "Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "KitKat", "Lollipop"};
private int mScrollY;
public NavigationAdapter(FragmentManager fm) {
super(fm);
}
public void setScrollY(int scrollY) {
mScrollY = scrollY;
}
#Override
protected Fragment createItem(int position) {
Fragment f = new ViewPagerTabListViewFragment();
if (0 < mScrollY) {
Bundle args = new Bundle();
args.putInt(ViewPagerTabListViewFragment.ARG_INITIAL_POSITION, 1);
f.setArguments(args);
}
return f;
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
}
ViewPagerTabListViewFragment.java
public class ViewPagerTabListViewFragment extends Fragment {
public static final String ARG_INITIAL_POSITION = "ARG_INITIAL_POSITION";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Activity parentActivity = getActivity();
final ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
setDummyDataWithHeader(listView, inflater.inflate(R.layout.padding, null));
if (parentActivity instanceof ObservableScrollViewCallbacks) {
// Scroll to the specified position after layout
Bundle args = getArguments();
if (args != null && args.containsKey(ARG_INITIAL_POSITION)) {
final int initialPosition = args.getInt(ARG_INITIAL_POSITION, 0);
ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
#Override
public void run() {
// scrollTo() doesn't work, should use setSelection()
listView.setSelection(initialPosition);
}
});
}
listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
}
return view;
}
protected void setDummyDataWithHeader(ListView listView, View headerView) {
listView.addHeaderView(headerView);
final ArrayList<String> list = Utils.getDummyList();
String[] array = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Utils.showToast(getActivity(), list.get(position).toUpperCase());
}
});
}
}
MainActivity- Layout.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
Padding for ViewPager must be set outside the ViewPager itself
because with padding, EdgeEffect of ViewPager become strange.
-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="48dp">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
<LinearLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/theme_green_dark"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/Theme.AppCompat.Light.DarkActionBar"
app:theme="#style/Toolbar"
android:elevation="4dp">
</android.support.v7.widget.Toolbar>
<!--<ImageView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="#dimen/dimen_160_dp"-->
<!--android:background="#color/loader_dark_color"/>-->
<com.callathome.consumer.widgets.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/tab_height"
android:background="#color/white"/>
</LinearLayout>
</FrameLayout>
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.callathome.consumer.fragment.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer"/>
Please help!
Thanks in advance.
It seems it's a problem inside the ObservableListView.
To intercept touch events, ObservableListView is designed to call its parent's onInterceptTouchEvent() and the parent -- in this case, the parent is ViewPager -- accidentally handles the touch event, which causes this behavior.
Anyway, I found a workaround for this.
Could you try this in your app?
Add an ID like to the root ViewGroup
in your MainActivity-Layout.xml, like android:id="#+id/root":
<FrameLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
Padding for ViewPager must be set outside the ViewPager itself
because with padding, EdgeEffect of ViewPager become strange.
-->
Then set this FrameLayout as TouchInterceptionViewGroup
to the ObservableListView in ViewPagerTabListViewFragment.java.
Maybe around listView.setScrollViewCallbacks() is good.
listView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.root));
listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
Ive tried to solve my Portrait/Landscape segment in my project using this tutorial:
http://www.cs.dartmouth.edu/~campbell/cs65/lecture09/lecture09.html
Everything seems to work fine (both landscape and portrait), but if i rotate from portrait to landscape or visa verse the app crashes with this: error
11-26 13:42:38.822 22594-22594/picturedtalk.com.picturedtalk E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: picturedtalk.com.picturedtalk, PID: 22594
java.lang.RuntimeException: Unable to start activity ComponentInfo{picturedtalk.com.picturedtalk/picturedtalk.com.picturedtalk.Signs.SignActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment picturedtalk.com.picturedtalk.Signs.DetailsFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3930)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment picturedtalk.com.picturedtalk.Signs.DetailsFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:601)
at android.app.FragmentState.instantiate(Fragment.java:98)
at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1759)
at android.app.Activity.onCreate(Activity.java:899)
at picturedtalk.com.picturedtalk.Signs.SignActivity.onCreate(SignActivity.java:16)
Any suggestion how i can stop the app from crashing when changing from portrait to landscape view?
That part of my app:
SignActivity.java
public class SignActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signs_layout);
}
}
ListFragment.java
public class ListFragment extends android.app.ListFragment {
private ArrayList<Signs> storage;
boolean mDualPane;
int mCurrentCheckPosition = 0;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SignAdapter adapter = new
SignAdapter(Storage.get(getActivity()).getStorageOfSigns());
setListAdapter(adapter);
//Check if the we are using layout-land version of the XML to figure out if
portrait/landscape
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
//restore last state
if (savedInstanceState != null) {
mCurrentCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
//only select one item at the time
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurrentCheckPosition);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurrentCheckPosition, true);
}
}
//Handle flipping during fragment use
//DOES NOT WORK
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("curChoice", mCurrentCheckPosition);
}
private void showDetails(int index) {
mCurrentCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
UUID startId = ((SignAdapter) getListAdapter()).getItem(0).getId();
details = new DetailsFragment(startId);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(!mDualPane){
Signs signs = ((SignAdapter) getListAdapter()).getItem(position);
Intent intent = new Intent(getActivity(),
picturedtalk.com.picturedtalk.Signs.DetailsActivity.class);
intent.putExtra(DetailsFragment.EXTRA_SIGN_ID, signs.getId());
startActivity(intent);
}
else{
UUID signId = ((SignAdapter) getListAdapter()).getItem(position).getId();
DetailsFragment fragment = new DetailsFragment(signId);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
private class SignAdapter extends ArrayAdapter<Signs> {
public SignAdapter(ArrayList<Signs> sSigns) {
super(getActivity(), 0, sSigns);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//If we were given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.signs_row,
null);
}
//Configure the view for this Crime
Signs signs = getItem(position);
TextView titleTextView = (TextView) convertView.findViewById(R.id.label);
titleTextView.setText(signs.getName());
return convertView;
}
}}
DetailsActivity.java
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
UUID mSignId;
mSignId = (UUID)getIntent().getSerializableExtra(DetailsFragment.EXTRA_SIGN_ID);
DetailsFragment details = new DetailsFragment(mSignId);
getFragmentManager().beginTransaction().replace(android.R.id.content, details).commit();
UUID STOPTHIs = mSignId;
}
else {
UUID mSignId;
mSignId = (UUID)getIntent().getSerializableExtra(DetailsFragment.EXTRA_SIGN_ID);
DetailsFragment details = new DetailsFragment(mSignId);
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}}
DetailsFragment.java
public class DetailsFragment extends Fragment {
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
public static final String EXTRA_SIGN_ID = "sign_id";
private UUID extraSignId;
// private static DetailsFragment detailsFragment;
private View view;
private TextView title;
private ImageView illustrativeView;
private ImageView pictureView;
private VideoView videoView;
private Signs mSign;
private String TAG = "DETAILFRAGMENT";
public DetailsFragment(UUID signId) {
this.extraSignId = signId;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSign = Storage.get(getActivity()).getSigns(extraSignId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.signs_details, container, false);
title = (TextView) view.findViewById(R.id.title);
illustrativeView = (ImageView) view.findViewById(R.id.illustrateImage);
pictureView = (ImageView) view.findViewById(R.id.pictureImage);
videoView = (VideoView) view.findViewById(R.id.videoView);
title.setText(mSign.getName());
try {
Bitmap illuBitmap = BitmapFactory.decodeFile(mSign.getIllustrativeURL());
illustrativeView.setImageBitmap(illuBitmap);
} catch (Exception e) {
Log.d(TAG, "failed loading illustrative image");
}
try {
Bitmap picBitmap = BitmapFactory.decodeFile(mSign.getImageURL());
pictureView.setImageBitmap(picBitmap);
} catch(Exception e){
Log.d(TAG, "failed loading picture image");
}
try {
Uri uri = Uri.parse(mSign.getVideoURL());
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
videoView.setBackgroundResource(R.drawable.simp);
return true;
}
});
videoView.start();
} catch (Exception e) {
Log.d(TAG, "failed loading video");
}
return view;
}}
Signs.java
public class Signs {
UUID id;
String name;
String videoURL;
String imageURL;
String illustrativeURL;
public Signs(String name, String imageURL,String videoURL, String illustrativeURL){
this.id = UUID.randomUUID();
this.name = name;
this.videoURL = videoURL;
this.imageURL = imageURL;
this.illustrativeURL = illustrativeURL;
}
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideoURL() {
return videoURL;
}
public void setVideoURL(String videoURL) {
this.videoURL = videoURL;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getIllustrativeURL() {
return illustrativeURL;
}
public void setIllustrativeURL(String illustrativeURL) {
this.illustrativeURL = illustrativeURL;
}}
signs_layout.xml (layout)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="picturedtalk.com.picturedtalk.Signs.ListFragment" />
signs_layout.xml (/layout-land)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/titles"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
class="picturedtalk.com.picturedtalk.Signs.ListFragment" />
<FrameLayout
android:id="#+id/details"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
signs_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:text="TitleHere"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="98dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/illustrateImage"
android:layout_below="#id/title"
android:layout_toRightOf="#+id/pictureImage"
android:background="#drawable/signs_logo"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pictureImage"
android:layout_centerVertical="true"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:background="#drawable/simp"/>
<VideoView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/videoView"
android:layout_below="#id/title"
android:layout_toLeftOf="#+id/pictureImage"/>
</RelativeLayout>
signs_listview.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
signs_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="20px" >
</TextView>
</LinearLayout>
You can avoid activity recreation by adding following to your application's manifest file.
as
android:configChanges="keyboardHidden|orientation|screenSize"
and
<activity
android:name=".your activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name" >
</activity>