话不多说,先看效果
首先是布局文件:
<LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="center" android:background="#fff" android:orientation="horizontal" android:paddingLeft="30dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginRight="10dp" android:src="@drawable/notice" /> <ViewFlipper android:id="@+id/flipper" android:layout_width="wrap_content" android:layout_height="34dp" android:layout_gravity="center" android:autoStart="true" android:background="@android:color/white" android:flipInterval="3000" android:inAnimation="@anim/push_up_in" android:outAnimation="@anim/push_up_out" /> </LinearLayout>Activity中的一些设置:
private ViewFlipper flipper; private List testList; private int count; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); flipper = findViewById(R.id.flipper); testList = new ArrayList(); testList.add(0, "我爱玛丽莲·梦露"); testList.add(1, "我爱奥黛丽·赫本"); testList.add(2, "我爱苍进空"); testList.add(3, "我爱斯嘉丽·约翰逊"); count = testList.size(); for (int i = 0; i < count; i++) { final View ll_content = View.inflate(this, R.layout.item_flipper, null); TextView tv_content = (TextView) ll_content.findViewById(R.id.tv_content); tv_content.setText(testList.get(i).toString()); flipper.addView(ll_content); } if (count == 1) { flipper.stopFlipping(); flipper.setAutoStart(false); } flipper.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(DemoActivity.this,testList.get(flipper.getDisplayedChild()).toString(),Toast.LENGTH_SHORT).show(); } }); }其中ll_content是自定义的需要轮播布局,通过ViewFinder的addView()方法添加
setAutoStart()方法是控制是否自动轮播,这里加了一句判断,当list的条目为1的时候取消自动轮播
getDisplayedChild()方法可以获取到当前轮播的元素位置
item的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#fff"> <TextView android:id="@+id/tv_content" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:text="BreakingNews" android:textColor="@android:color/black" android:textSize="12sp"></TextView> </LinearLayout>ok,笔记做完了。