MVVMCross Fragment and dynamically setting event commands - android-fragments

I have a MvxFragment that is bound to a view model that has two ICommand properties defined. This fragment contains an MvxListView and can be part of different activities/layouts dependant on the device size/orientation.
What I want to know is how to specify the ItemClick event command of the MvxBind property of the MvxListView dynamically or is there a better way to handle this use case? Should I use a separate fragment?
A similar use case to the one I am trying to achieve is within the Overview section of this Xamarin Dev Guide
View
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<MvxListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
local:MvxBind="ItemsSource Courses; ItemClick Comamnd1"
local:MvxItemTemplate="#layout/coursetemplate" />
</LinearLayout>
ViewModel (Simpified)
public class MyViewModel : MvxViewModel
{
private MvxCommand<MyMessage> messageCommand;
public MyViewModel (IMvxMessenger messenger, IHttpClientBuilderService httpClientBuilder)
{
this.httpClientBuilder = httpClientBuilder;
this.messenger = messenger;
}
public ICommand Comamnd1 {
get { return new MvxCommand<Course> ((c) => ShowViewModel<MyOtherViewModel>(c)); }
}
public ICommand Command2 {
get
{
messageCommand = messageCommand ?? new MvxCommand<MyMessage>(c =>
{
var message = new MyMessage(this, c);
messenger.Publish(message);
});
return selectedCourse;
}
}
}

OK, you can do this my overriding the OnActivityCreated event for the fragment as below.
public override void OnActivityCreated (Bundle savedInstanceState)
{
base.OnActivityCreated (savedInstanceState);
MvxListView list = Activity.FindViewById<MvxListView>(Resource.Id.[theID]);
if (Activity.FindViewById<View>(Resource.Id.[fragmentID]) != null)
list.ItemClick = ((MyViewModel)ViewModel).Command1;
else
list.ItemClick = ((MyViewModel)ViewModel).Command2;
}
You can pull out the list by using the Activity.FindViewById function and then set the appropraite ICommand or IMvxCommand from the ViewModel via the list.ItemClick event

Related

Overlapping of fragments when transiting on clicking on an item in RecyclerView of one fragment to another new fragment

I am new to android development. The problem is the RecyclerView populated using a firebase database is not replaced by a new fragment, rather the new fragment is on top, but clicking on another item of the recycler view still works, which I checked using a toast in the new fragment. I know that the next fragment is there because I have TextView at the bottom, which is visible on clicking on the recycler view Item.
Here is my code
adapter = new FirebaseRecyclerAdapter<Categories, CategoryViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final CategoryViewHolder holder, int position, #NonNull Categories model)
{
Picasso.get().load(model.getImage()).placeholder(R.drawable.camera).into(holder.categoryImage, new Callback() {
#Override
public void onSuccess()
{
}
#Override
public void onError(Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.categoryName.setText(model.getName());
holder.categoryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), holder.categoryName.getText().toString(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(getActivity(), ProductListActivity.class);
// startActivity(intent);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
SearchFragment fragment = SearchFragment.newInstance(holder.categoryName.getText().toString());
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, fragment, SearchFragment.class.getSimpleName());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
The fragment I am using is also used for the navigation drawer using navController.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</RelativeLayout>
Edit: I have another recyclerView inside SearchFragment, which didn't show after I clicked an image in the RecyclerView(One which calls SearchFragment). But it showed after I minimized and opened the app again. I don't understand why that is happening.
I just found an easy way to move from one fragment to another without using FragmentManager. I hope this helps others, it worked for me. Initialize the NavController in the first fragment inside onCreateView
navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
And adding the following for transition
Bundle bundle = new Bundle();
bundle.putString("Category", holder.categoryName.getText().toString());
navController.navigate(R.id.nav_category_product_list, bundle);
to get the argument in the moving fragment type this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); //To get menu items at the top
if (getArguments() != null) {
Category = getArguments().getString("Category");
}
}
Also, add this transition in Navigation graph XML
.
.
.
<fragment
android:id="#+id/nav_category"
android:name="com.grocery.admin.ui.category.CategoryFragment"
android:label="#string/menu_category"
tools:layout="#layout/fragment_category" >
<action
android:id="#+id/action_nav_category_to_nav_category_product_list"
app:destination="#id/nav_category_product_list" />
</fragment>
<fragment
android:id="#+id/nav_category_product_list"
android:name="com.grocery.admin.ui.category.CategoryProductFragment"
android:label="Product List"
tools:layout="#layout/fragment_category_product">
</fragment>
.
.
.

ListView ID called on null? (Kotlin)

I'm new to Kotlin and im trying to build a HomePage where there is a BottomNavigation with 3 Fragment pages but in 1 of the pages I set a ListView and whenever I call the ID it gives the following errer(Caused by: java.lang.IllegalStateException: categoryListView must not be null)
Here is how Im calling it in my HomePage which is where the content appears:
class HomePage : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
lateinit var adapter : CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
adapter = CategoryAdapter(this, DataService.categories)
categoryListView.adapter = adapter
navView.setNavigationItemSelectedListener(this)
bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
replaceFragment(HomeFragment())
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when(item.itemId) {
R.id.Bottom_Nav_Home -> {
println("Home pressed")
replaceFragment(HomeFragment())
return#OnNavigationItemSelectedListener true
}
R.id.Bottom_Nav_Notifs -> {
println("Notification pressed")
replaceFragment(NotifsFragment())
return#OnNavigationItemSelectedListener true
}
R.id.Bottom_Nav_List -> {
println("List pressed")
replaceFragment(ListFragment())
return#OnNavigationItemSelectedListener true
}
}
false
}
private fun replaceFragment(fragment: Fragment) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.NavPageFragment, fragment)
fragmentTransaction.commit()
}
}
am I doing it correct? or am I supposed to call the categoryListView elsewhere? because I tried in my ListFragment which is where my activity code is and it gave a context error
here is how the Fragment activity looks:
<?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:id="#+id/Bottom_List"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.ListFragment">
<ListView
android:id="#+id/categoryListView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You are trying to get the categoryListView resolved inside the activity but it is (as far as I understand) part of the fragment. This simply does not work.
The CategoryAdapter and the ListView should be used inside your HomeFragment class and this will work then.
So move this code into your fragment:
adapter = CategoryAdapter(this, DataService.categories)
categoryListView.adapter = adapter
Update
I would move it into the onViewCreated() method. There you can simply rely on the fact that there is a view available with a context.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
adapter = CategoryAdapter(view.context, DataService.categories)
categoryListView.adapter = adapter // categoryListView will be not null here
}

how to replace a fragment in kotlin from a onclicklistener inside a recyclerview

How can I replace the fragment when i click on an item inside a recyclerView
I've tried inside onClickListener of adapter
childFragmentManager
.beginTransaction()
.replace(R.id.framefragment2, Fragment2())
.commit()
with no succes it returns me
java.lang.IllegalArgumentException: No view found for id 0x7f0a0137 (com.test.justaapp:id/framefragment1) for fragment Fragmetnone{1ebd5fc #0 id=0x7f0a0137}
Here is mi xml of 1st fragment already inflated
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/framefragment1"
android:layout_width="match_parent"
android:layout_height="match_parent">
and the second frame layout
<FrameLayout 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:background="#C0C0C0">
<FrameLayout
android:id="#+id/framefragment2"
android:layout_width="match_parent"
android:layout_height="match_parent">
I've been searching for hours and can't get it to work, any ideas? maybe I'm mimssing something very simple, any help would be apreciated Greets.
You can implement an interface on your ViewHolder, then you pass an implementation of this interface to your adapter from your activity. In your adapter your pass the implementation when you create the CustomViewHolder instance (create method).
In your activity/fragment:
private val adapter = YourAdapter(object: CustomViewHolder.Listener {
fun onClick() {
// change the fragment here with the fragment manager of your activity/fragment.
}
})
In your adapter:
class YourAdapter(private val listener: CustomViewHolder.Listener): RecyclerView.Adapter {
...
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return CustomViewHolder(
LayoutInflater.from(context).inflate(R.layout.view_layout, parent, false),
listener
)
}
}
ViewHolder implementation:
class CustomViewHolder(view: View, private val listener: Listener): ViewHolder(view) {
...
interface Listener {
fun onClick()
}
fun onCreate(parent: View, listener: Listener): CustomViewHolder {
// inflate the view and return an instance of CustomViewHolder
}
fun onBind() {
button.setOnClickListener {
listener.onClick()
}
}
}
I didn't test this code but the logic is here. You just need to adapt it to your project.

getChildFragmentManager() and viewpager

I have the same problem as Navigating back to FragmentPagerAdapter -> fragments are empty but would like some clarification on the solution of using getChildFragmentManager().
This solution uses getChildFragmentManager(), the manager for fragments inside this Fragment(OuterFragment, which has the viewpager). InnerFragment is a page inside OuterFragment. When someone clicks the listview in InnerFragment, I want InnerFragment2 to replace InnerFragment. What do the xml and fragment managers look like?
fragment_outer.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vpPager"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_gravity="top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
<FrameLayout
android:id="#+id/inner_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.view.ViewPager>
OuterFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_outer, container, false);
vpPager = (ViewPager) v.findViewById(R.id.vpPager);
FragmentManager cfManager = getChildFragmentManager();
adapterViewPager = new MyPagerAdapter(cfManager);
vpPager.setAdapter(adapterViewPager);
return v;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return 2;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return InnerFragment.newInstance(false);
case 1:
return InnerFragment.newInstance(true);
default:
return null;
}
}
InnerFragment shows up as a fragment inside OuterFragment, which has the viewpager. InnerFragment has a listview that when clicked, should replace InnerFragment with InnerFragment2.
InnerFragment.java:
FragmentManager fm = getChildFragmentManager();
fm = fm.beginTransaction();
ft.addToBackStack(null);
ft = ft.replace(R.id.inner_content,
InnerFragment2.newInstance(someArg));
ft.commit();
This throws an error saying InnerFragment2 does not recognize view R.id.inner_content.
Not only should InnerFragment2 replace InnerFragment, but when InnerFragment2 is shown and it's button is clicked, I want InnerFragment2 replaced with InnerFragment3. I basically want to use inner_content as an inner container and keep adding fragments to a backstack for appropriate back behavior.
Do I getChildFragmentManager() or getFragmentManager() each time I add to my fragment backstack, what does the xml pattern look like, because having one framelayout in my outerfragment isn't doing it.
public void setupViewPager(ViewPager viewPager) {
FragmentManager cfManager=getChildFragmentManager();
viewPagerAdapter = new ViewPagerAdapter(cfManager);
// viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerAdapter.addFragment(new EntertainmentWallpaperFragment(), getString(R.string.title_entertainment_wallpapers));
viewPagerAdapter.addFragment(new EntertainmentMusicFragment(), getString(R.string.title_entertainment_music));
viewPagerAdapter.addFragment(new EntertainmentGamesFragment(), getString(R.string.title_entertainment_games));
viewPagerAdapter.addFragment(new EntertainmentEBooksFragment(), getString(R.string.title_entertainment_ebooks));
viewPagerAdapter.addFragment(new EntertainmentAppsFragment(), getString(R.string.title_entertainment_apps));
viewPager.setAdapter(viewPagerAdapter);
}
I hope this helps. I had the same problem where the fragments apear but once you go back they dissapear and find an empty fragent. Commnented the line that I had first implemented which after updating the fragment manager I was able to enjoy free smooth scroll.

Fragment seems to inflate wrong view

I'm currently trying to program an Android Launcher with Fragments but I have problems with the Views on the Fragments.
I have a Dock-Fragment with a Dock-Controller which allow the user to change fragments, such as apps menu, settings fragment etc. The Dock is displayed on the buttom of the display, the Fragments(apps menu, settings fragment) should be displayed above the Dock.
The problem is, that the apps menu is not shown in its associated Fragment but rather in the Dock Fragment behind the dock icons,... So I guess, the app menu fragment gets the wrong view in its onCreateView()-Method, but I don't get why.
This is the code of the MainActivity that extends from FragmentActivity. I add the fragments to the manager.
private void addDockToManager() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(dbConnection.getLayout(DOCK_TAG), dockController.getFragment(), DOCK_TAG);
ft.commit();
}
private void addPluginsToManager() {
FragmentManager fm = null;
FragmentTransaction ft = null;
for(String key : controllerMap.keySet()) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
FrameController controller = null;
if ((controller = controllerMap.get(key)) != null) {
ft.add(dbConnection.getLayout(key), controller.getFragment(), key);
if (key.equals(standardFrame))
ft.addToBackStack(key);
}
ft.commit();
fm.executePendingTransactions();
}
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
for(String key : controllerMap.keySet()) {
if (controllerMap.get(key) != null && !key.equals(standardFrame)) {
ft.hide(fm.findFragmentByTag(key));
}
}
ft.commit();
}
The layouts are hardcoded at the moment in dbConnection:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
The MainActivity's xml looks like that:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.activity.MainActivity"
tools:ignore="MergeRootFrame" >
<FrameLayout
android:id="#+id/fl_settings"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_app_menu"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_dock"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</FrameLayout>
</RelativeLayout>
The xml of the apps menu is a gridview and looks like that:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_apps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="6"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth" >
</GridView>
The App Fragment looks like that:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.external_apps, group, false);
layout = (GridView) view.findViewById(R.id.gv_apps);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GridViewAdapter gridViewAdapter = new GridViewAdapter((AppMenuController) myController, apps);
((GridView) layout).setAdapter(gridViewAdapter);
}
And the getView Method of the GridViewAdapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(controller.getMainActivity().getApplicationContext());
imageView.setImageDrawable(buttons.get(position).getIcon());
imageView.setLayoutParams(new GridView.LayoutParams(65, 65));
return imageView;
}
I hope what I mentioned is enough to resolve the problem. I am searching the web for hours but I found no solution.
It's a much simpler problem than that I think.
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
Should be:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" :
layout = R.id.fl_app_menu;
break;
case "settings" :
layout = R.id.fl_settings;
break;
case "dock" :
layout = R.id.fl_dock;
break;
}
return layout;
}
Because switch-case structure is still essentially just an organized goto, and not actually an if-else structure, aka if you don't break out, then all cases will run sequentially.
I found the problem. And it was in a part of the code I never expected it to be.
The Dummy-Switch-Case in dbConnection caused it. Seemingly Strings aren't compared by value but rather by reference in such a Switch-Case. So it always chose the dock container layout to be associated with the app menu in the fragment manager,...

Resources