从活动中显示/隐藏ListView

时间:2013-10-17 21:12:15

标签: java android android-listview

我希望通过按钮切换ListView的可见性,但当我使用@android:id/list进行ListView时,我不知道如何通过findViewById(R.id. list);检索Activity中的视图:

为此,我有以下代码:

public void feedButtonListener() {

    final ImageButton ToggleButton = (ImageButton) findViewById(R.id.ToggleFeed);

    ToggleButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Toast.makeText(MainActivity.this, "Toggleis clicked!",
                    Toast.LENGTH_SHORT).show();
            ListView listView = (ListView) findViewById(R.id.list); //HOW?
            if (feedView) {
                listView.setVisibility(View.GONE); 
                ToggleButton
                        .setImageResource(R.drawable.ic_inactive);
                feedView = false;
            } else {
                listView.setVisibility(View.VISIBLE);
                ToggleButton
                        .setImageResource(R.drawable.ic_active);
                feedView = true;

            }
        }

    });

在布局中:

<ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginBottom="@dimen/margin"
        android:layout_marginTop="@dimen/margin" >
</ListView>

1 个答案:

答案 0 :(得分:3)

ListView listView = (ListView) findViewById(android.R.id.list); //thats how :)

注意前面的android: android .R.id.list

如果您在ListFragmentListActivity,则可以致电

ListView listView = getListView();