Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility of ImageButton in MVVMCross

I have the following axml where I have two image buttons, but I only want to show one at a time and implement something toggle feature.

More specifically, when a user clicks on button1, it will hide button1 and will show button2 and vice versa. I am using MVVMCross pattern.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp">
    <ImageButton
        android:id="@+id/myBtn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_arrow_back" />
    <ImageButton
        android:id="@+id/myBtn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_arrow_white" />
</RelativeLayout>
like image 921
casillas Avatar asked Jan 07 '23 06:01

casillas


1 Answers

I would use the Visibility Plugin (add it from NuGet)

Then add: a bool property and a command to switch the bool in the ViewModel:

private bool _boolInViewModel; 
public bool BoolInViewModel
{
    get { return _boolInViewModel; }
    set { _boolInViewModel = value; RaisePropertyChanged(() => BoolInViewModel);}
}

public IMvxCommand CommandToSwitchBool
{
    get
    {
        return new MvxCommand(()=>
            {
                BoolInViewModel = !BoolInViewModel;
            }
        );
    }
}

and then Bind to to the bool with the visibility converter and inverted visibility convert and the command to the click event on the buttons like so:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">
        <ImageButton
            android:id="@+id/myBtn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_back"
            app:MvxBind="Visibility Visibility(BoolInViewModel); Click CommandToSwitchBool"/>
        <ImageButton
            android:id="@+id/myBtn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_white"
            app:MvxBind="Visibility InvertedVisibility(BoolInViewModel); Click CommandToSwitchBool"/>
    </RelativeLayout>
</LinearLayout>
like image 181
Iain Smith Avatar answered Feb 04 '23 08:02

Iain Smith