ViewFlipper / ViewSwitcher第二视图为空

时间:2016-07-07 09:57:38

标签: android viewflipper viewswitcher

我是Android编程的新手,现在我想为2个视图创建一个ViewFlipper或ViewSwitcher,它将在1到2列之间切换视图。问题是第一个视图没问题,但是当我使用showNext()或showPrevious()时,第二个视图显示为空白,我完全忘记了什么是错的。我尝试过ViewFlipper和ViewSwitcher的结果相同。

layout_devicelistmainswitcher.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">


<Button
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:contentDescription="Grid/List View"
    android:id="@+id/viewbutton"
    android:background="@drawable/viewicon"
    android:layout_gravity="right" />

<ViewFlipper
        android:id="@+id/vflipper"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <GridView
                android:numColumns="1"
                android:gravity="center"
                android:columnWidth="100dp"
                android:stretchMode="columnWidth"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/grid"
                android:scrollbars="none" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="200dp"
            android:layout_height="200dp">

            <GridView
                android:numColumns="2"
                android:gravity="center"
                android:columnWidth="100dp"
                android:stretchMode="columnWidth"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/grid_l"
                android:scrollbars="none" />
        </LinearLayout>

</ViewFlipper>

mainactivity.java

public class  activity_devicelist extends AppCompatActivity {

GridView grid;
Boolean viewtype = true;
ViewFlipper switcher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_devicelistmainswitcher);

    Button button = (Button) findViewById(R.id.viewbutton);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(activity_devicelist.this, "Button Clicked", Toast.LENGTH_SHORT).show();
            switcher = (ViewFlipper) findViewById(R.id.vflipper);
            switcher.showPrevious();
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

将你的findViewById移出如下,然后它应该工作

switcher = (ViewFlipper) findViewById(R.id.vflipper);

 button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(activity_devicelist.this, "Button Clicked", Toast.LENGTH_SHORT).show();

        switcher.showPrevious();
    }
});