在片段中使用smoothScrollTo



我有以下情况:

我使用导航抽屉让用户可以轻松地在不同的主题之间导航。

你可以在这里找到图片:

https://drive.google.com/file/d/0B2gMUEFwlGRfSHRzVlptYmFQTXc/edit?usp=sharing

当单击标题时,如General,通过使用片段和布局文件,只会替换主要内容视图。但是,当用户单击副标题时,如Gameplay,布局会发生变化,并且应该向下滚动到布局中的特定视图。

因此,在我的片段类中,我使用了由ScrollView提供的"onViewCreated"方法和smoothScrollTo方法。ScrollView和RelativeLayout都不为空,并设置为正确的id,设置在"onCreateView"中

代码片段:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments().getBoolean(ARG_BOOL)) {
scrollView = (ScrollView)getView().findViewById(scrollID);
relativeLayout = (RelativeLayout)getView().findViewById(relativeID);
((ScrollView)getView().findViewById(scrollID)).smoothScrollTo(
0, (getView().findViewById(relativeID)).getLeft());
Toast.makeText(getApplicationContext(), "SCROLL",Toast.LENGTH_SHORT).                  
show();
}
}

问题是,在执行toast时,它没有执行"smoothScrollTo"方法。

这里我调用片段(布尔滚动用于控制smoothScrollTo方法):

private void selectItem(int Id, boolean scroll) {
Fragment fragment = new ContentFragment();
Bundle args = new Bundle();
args.putBoolean(ContentFragment.ARG_BOOL, scroll);
args.putInt(ContentFragment.ARG_ITEM_ID, Id);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
TextView textView = (TextView) findViewById(Id);
getActionBar().setTitle(textView.getText());
mDrawerLayout.closeDrawer(mDrawerList);
} 

谢谢你的帮助;-)

编辑:解决方案:

if (getArguments().getBoolean(ARG_BOOL)) {
getView().findViewById(scrollID).post(new Runnable() {
@Override
public void run() {
((ScrollView) getView().findViewById(scrollID)).
smoothScrollTo(0, (getView().findViewById(relativeID)).getTop());
}
});
}

在调用视图的post时尝试调用smoothScrollTo方法:

ScrollView scrollView = (ScrollView)getView().findViewById(scrollID);
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0,(getView().findViewById(relativeID)).getTop());
}
});

最新更新