简体   繁体   中英

How to use the same id for 2 views of different types

I have 2 scroll views, one in portrait layout, and the other in the horizontal layout (layout-land), and in onCreate I use findViewById using the shared id, the problem is, that one of them is ScrollView and the other is HorizontalScrollView which causes the following exception when I rotate the mobile:

Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.ScrollView$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/mainscreen_scrollview. Make sure other views do not use the same id.

The code behind the reason I gave the same ID for both ScrollViews, the code below is in onCreate(....)

    mHomeScrollView = (FrameLayout) findViewById(R.id.mainscreen_scrollview);

    mHomeScrollView.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event){
            return mGestureDetector.onTouchEvent(event);
        }
    });

Edit 1:

Based on the discussion with respectful members, seems that this is the most appropriate solution, I hope it might help others:

    int scrollViewId = R.id.mainscreen_scrollview;
    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
        scrollViewId = R.id.mainscreen_horizontalscrollview;
    }

You have taken same ScrollView id for both of the Scrollview

Error:

Make sure other views do not use the same id.

id is homescreen_scrollview

Note : Both scrollView Id should be different.

By creating two layout files with the same name but in different directories (eg layout & layout_land) you can assign to the same object two identical ids. Simply set the id like android:id="@+id/my_id" to both. Be careful: Both have to be part of the same object (eg both ScrollViews).

I am not sure about this but you can try this and tell us if it work.

scrollView var1= (scrollview) var.findViewByID(R.id.first_scroll_view);

HorizontalScrollView  var2 = (HorizontalScrollView) var2.findViewByID(R.id.second_scroll_view)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM