how to use viewswitcher with same id's in both layouts

683 Views Asked by At

I am using view switcher in my project.

In my xml I have created 2 layouts with all same Id's. After I switch my view I can not switch to previous view because I am using same ID's in both layouts.

Now how can I use one listener in java code for both layouts in view switcher. I dont want to create an another id and create another listener to switch again.

My xml is as below.

<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/profileSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/switchBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Switch" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/switchBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Switch" />
</RelativeLayout>

</ViewSwitcher>

My java code is as follows

final ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.profileSwitcher);
    Button btn = (Button) findViewById(R.id.switchBtn);
    btn.setOnClickListener(new OnClickListener() {

        private boolean switchCheck;

        public void onClick(View v) {
            new AnimationUtils();
            switcher.setAnimation(AnimationUtils.makeInAnimation(getApplicationContext(), true));
            if (!switchCheck) {
                switcher.showNext();
                switchCheck = true;
            } else {
                switcher.showPrevious();
                switchCheck = false;
            }
        }
    });

Please help..

2

There are 2 best solutions below

1
On

Crete different ids for parent relative layout in xml.

And then in java file check which relative layout button is used. using method

step 1)

RelativeLayout r1 =  RelativeLayout findviewbyId(R.id.rl1)
RelativeLayout r2 =  RelativeLayout findviewbyId(R.id.rl2)

step2)

if button.getParent equals to R1 then ... 
else .....
0
On

Just try to change ur text in any of the button or textView .may be ur view is switching but because the code for both the layouts is exactly same u r not able to differentiate.