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 ?
Related
I have a fragment named "Notification fragment" in which I want to show another fragment named "Watching Fragment" using Tab layout . When I run the app, the tab layout bar is visible but the fragments are not visible.
My Fragment inside which other fragments are to be shown (Notifications Fragment)
public class NotificationsFragment extends Fragment{
GridView listv;
FragmentAdapter fragmentAdapter;
private NotificationsViewModel notificationsViewModel;
private FragmentNotificationsBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
notificationsViewModel =
new ViewModelProvider(this).get(NotificationsViewModel.class);
binding = FragmentNotificationsBinding.inflate(inflater, container, false);
View root = binding.getRoot();
TabLayout tabLayout = root.findViewById(R.id.tabLayout);
ViewPager vp = root.findViewById(R.id.vp2);
fragmentAdapter = new FragmentAdapter(getChildFragmentManager() , tabLayout.getTabCount());
vp.setAdapter(fragmentAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
vp.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 0 || tab.getPosition() == 1 || tab.getPosition() == 2)
fragmentAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
vp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return root; }
My First Fragment (Watching Fragment)
public class WatchingFragment extends Fragment {
ArrayList<String> list = new ArrayList<String>();
GridView gridv1;
private WatchingViewModel mViewModel;
public static WatchingFragment newInstance() {
return new WatchingFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.watching_fragment, container, false);
gridv1 = view.findViewById(R.id.gridv1);
Intent intent = getActivity().getIntent();
String animename = intent.getStringExtra("nameanime");
list.add(animename);
loadData2();
saveData2();
ListNewAdapter adapter = new ListNewAdapter(getContext(), R.layout.watch_list, list);
gridv1.setAdapter(adapter);
gridv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
list.remove(position);
adapter.notifyDataSetChanged();
saveData2();
return true;
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(WatchingViewModel.class);
// TODO: Use the ViewModel
}
private void saveData2() {
SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
ed.putString("anime list", json);
ed.apply();
}
private void loadData2() {
SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("anime list", "");
Type type = new TypeToken<ArrayList<String>>() {}.getType();
list = gson.fromJson(json , type);
if (list == null) {
list = new ArrayList<String>();
}
}
}
My View pager adapter
public class FragmentAdapter extends FragmentPagerAdapter {
int tabcount;
public FragmentAdapter(#NonNull #NotNull FragmentManager fm, int behavior) {
super(fm, behavior);
tabcount = behavior;
}
#NonNull
#NotNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new WatchingFragment();
case 1: return new CompletedFragment();
case 2: return new WantToWatchFragment();
default: return null;
}
}
#Override
public int getCount() {
return 0;
}
}
Notifications Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.notifications.NotificationsFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Watching" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Completed" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Want To Watch" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/vp2"
android:name="com.example.animeguide.ui.notifications.NotificationsFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
Watching Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.notifications.FragmentsInsideList.watching.WatchingFragment">
<TextView
android:id="#+id/textView4"
android:layout_width="184dp"
android:layout_height="58dp"
android:text="hello world"
android:textSize="34sp" />
<GridView
android:id="#+id/gridv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2" />
</LinearLayout>
In order for the Adapter to know how many pages it has, you need to override getCount method. You did override it, but used 0 as the number of pages, thus having no pages.
In your FragmentAdapter class, try changing this:
#Override
public int getCount() {
return 0;
}
To this:
#Override
public int getCount() {
return tabcount;
}
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 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 a dialog fragment and I need to launch a fragment within this dialog fragment. This means my fragment should occupy the same window as that of dialog fragment. How do I do this? This is my dialog fragment code -
public class CallDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.call_dialog_fragment, container, false);
return view;
}
}
Just use fragment transaction and add another dialog fragment. and add to back stack.
you can use coordinator layout for dialog-fragment.. when you drag layout to upper side it will be your new fragment. and when you drag to down it will be your dialog fragment.
here is the xml code..
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_backdrop_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
local:contentScrim="?attr/colorPrimary"
local:expandedTitleMarginEnd="64dp"
local:expandedTitleMarginBottom="22dp"
local:expandedTitleMarginStart="20dp"
local:expandedTitleTextAppearance="#style/TextAppearance.AppCompat.Title"
local:layout_scrollFlags="scroll|exitUntilCollapsed">
<ProgressBar
android:id="#+id/progressfull"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_marginTop="80dp"
android:layout_height="24dp" />
<ImageView
android:id="#+id/image_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
local:layout_collapseMode="parallax"
/>
<View
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/image_preview"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarIcon"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
local:borderWidth="0dp"
android:layout_marginRight="#dimen/fab_margin"
android:layout_marginLeft="#dimen/fab_margin"
android:layout_marginTop="#dimen/fab_margin"
android:layout_marginBottom="25dp"
android:src="#drawable/ic_add" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:background="#color/colorPrimaryDark"
local:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
fragment_image_slider.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
here is the java code..
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ArrayList<ItemCategories> images;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private String lblCount, lblTitle, lblDate;
private int selectedPosition = 0;
private CardView cardView;
private Context mContext;
public static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment fragmentFullScreen = new SlideshowDialogFragment();
return fragmentFullScreen;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
setHasOptionsMenu(true);
ViewCompat.setOnApplyWindowInsetsListener(viewPager,
new OnApplyWindowInsetsListener() {
#Override
public WindowInsetsCompat onApplyWindowInsets(View v,
WindowInsetsCompat insets) {
insets = ViewCompat.onApplyWindowInsets(v, insets);
if (insets.isConsumed()) {
return insets;
}
boolean consumed = false;
for (int i = 0, count = viewPager.getChildCount(); i < count; i++) {
ViewCompat.dispatchApplyWindowInsets(viewPager.getChildAt(i), insets);
if (insets.isConsumed()) {
consumed = true;
}
}
return consumed ? insets.consumeSystemWindowInsets() : insets;
}
});
images = (ArrayList<ItemCategories>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
Log.e(TAG, "position: " + selectedPosition);
Log.e(TAG, "images size: " + images.size());
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
getArguments().remove("position");
getArguments().remove("images");
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void displayMetaInfo(int position) {
lblCount = (position + 1) + " of " + images.size();
ItemCategories image = images.get(position);
lblTitle = "" + image.getCategoryItem();
lblDate = "" + image.getUrlThumb();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyMaterialThemeFull);
}
#Override
public void onDetach() {
super.onDetach();
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Toolbar toolbarIcon = (Toolbar) view.findViewById(R.id.toolbarIcon);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbarIcon);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.appbar);
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenHeight = displaymetrics.heightPixels;
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams();
lp.height = screenHeight;
toolbarIcon.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("slideshow");
if (prev != null) {
DialogFragment dialogFullScreen = (DialogFragment) prev;
dialogFullScreen.dismiss();
}
}
});
ItemCategories image = images.get(position);
Glide.with(getActivity()).load(image.getUrlThumb())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
collapsingToolbar.setTitle(lblTitle);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
just copy this code and you will know what i am talking about
I'm trying to update textview in fragment from another activity. But I'm getting a NUllPointerException when calling the setText method. I have tried the following, but still getting the NPE.
1. Tried accessing the fragments textview with FindViewbyId in activity.
2. Tried using a method in fragment and calling it from activity and passing the value as parameters
FragHome Activity
public class FragHome extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
Handler bluetoothIn;
private static TextView tmpF, humF, CoF;
String tempGL, HumGL, coGL, devname;
double dblTemp, dblCo;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_home);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Temperature"));
tabLayout.addTab(tabLayout.newTab().setText("Humidity"));
tabLayout.addTab(tabLayout.newTab().setText("CO"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
bluetoothIn=new Handler() {
String readMessage;
String[] values = new String[]{""};
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
readMessage = (String) msg.obj;
values = readMessage.split("#");
for (int j = 0; j < values.length; j++) {
int rem = j % 3;
if (rem == 0) {
tmpF.setText(values[j] + " C");
tempGL = String.valueOf(values[j]);
try {
dblTemp = Double.parseDouble(tempGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 1) {
CoF.setText(values[j] + " ppm");
coGL = values[j];
try {
dblCo = Double.parseDouble(coGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 2) {
humF.setText(values[j] + " %");
HumGL = values[j];
}
}
}
}
};
btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Pager
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Tab1
public class OneFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="shinil.tablayout.OneFragment"
android:id="#+id/rltnvnv">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textviewtemp"
android:layout_centerInParent="true"/>
</RelativeLayout>
frag_home.xml
LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- our toolbar -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The NPE occurs when I try to settext from the activity. Please help
Use below callback:
Fragment Class:
public class FragmentOne extends Fragment {
private ViewCallback mCallback;
public FragmentOne(ViewCallback mCallback) {
this.mCallback = mCallback;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
return view;
}
public interface ViewCallback {
void updateTextView(TextView view);
}
}
Below is the Activity class:
public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {
public TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callback);
FragmentOne fragment = new FragmentOne(this);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();
}
#Override
protected void onResume() {
super.onResume();
if (textView != null)
textView.setText("Updating Fragment TextView in Activity..!!");
}
#Override
public void updateTextView(TextView view) {
this.textView = view;
}
}
Implment that call back in your activity class..then update the textview.