我想实现一个视图选择器,它就像一个数字视图选择器,但不是选择数字,而是选择拾取器中心的视图。
基本思想是获取居中项目的位置,并用不同的视图替换该位置的视图。为此,我做了以下 -
我有以下布局 -
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<View
android:id="@+id/view"
android:background="#ffeb3b"
android:layout_gravity="center"
android:layout_height="56dp"
android:layout_width="match_parent" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rvItems"
android:clipToPadding="false"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</FrameLayout>
填充视图的活动是 -
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView rvItems;
private View view;
private List<Data> array = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i=0; i< 100; i++) {
final Data data = new Data();
data.isVisible = true;
data.data = String.valueOf(i);
array.add(data);
}
view = (View) findViewById(R.id.view);
rvItems = (RecyclerView) findViewById(R.id.rvItems);
rvItems.setAdapter(new SliderAdapter(array));
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rvItems.setLayoutManager(layoutManager);
rvItems.post(new Runnable() {
@Override
public void run() {
int firstVisibleChildPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
int lastVisibleChildPosition = layoutManager.findLastCompletelyVisibleItemPosition();
int centerChildPosition = (firstVisibleChildPosition + lastVisibleChildPosition) / 2;
for (int i=0; i < centerChildPosition; i++) {
final Data data = new Data();
data.isVisible = false;
// Adding empty list at begining and end of position
array.add(0, data);
array.add(array.size(), data);
}
rvItems.getAdapter().notifyDataSetChanged();
}
});
rvItems.addOnScrollListener(new RecyclerView.OnScrollListener() {
int centerChildPosition = -1;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int firstVisibleChildPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
int lastVisibleChildPosition = layoutManager.findLastCompletelyVisibleItemPosition();
centerChildPosition = (firstVisibleChildPosition + lastVisibleChildPosition) / 2;
recyclerView.scrollToPosition(centerChildPosition);
}
Log.d(TAG, "center position = " + centerChildPosition );
}
});
}
}
使用上面的代码,我能够知道居中的子位置,但无法在黄色矩形视图中正确拟合 -
如何确保数字在黄色栏内?现在,我在列表的顶部和底部添加了空视图,以便列表中的第一个和最后一个项可以居中。什么是最佳方式?