第一种方法:
在.xml文件中将这两个List分别放入不同的布局管理器中,比如说
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/citylist_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ExpandableListView android:id="@+id/expandablelist" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="36.56" android:background="#ffffff" android:cacheColorHint="#00000000" android:childDivider="@android:color/darker_gray" android:divider="@android:color/black" android:dividerHeight="1.5dip" android:listSelector="#00000000" /> </LinearLayout> <LinearLayout android:id="@+id/localmap_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffcc99" android:visibility="visible" > </ListView> </LinearLayout> </RelativeLayout>
上面一个ExpandableListView 一个ListView分别放入两个
LinearLayout布局中。
在MainActivity.java文件中写入如下代码
LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout); LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout); lm.setVisibility(View.VISIBLE); cl.setVisibility(View.GONE); LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout); LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout); lm.setVisibility(View.GONE); cl.setVisibility(View.VISIBLE);
就可实现两个ListView在同一时刻只出现一个。
<友情提示 View.GONE 不要替换成 View.INVISIBLE 可能出错
希望能搞明白
View.GONE
View.VISIBLE
View.INVISIBLE
三者的区别
>
第二种方法:使用Fragment
需要注意的是,如果报错如
java.lang.IllegalStateException The specified child already has a parent. You must call removeView() on the child's parent first
我犯错的原因是在继承Fragment的子类实现方法
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View =inflater.inflate(R.layout.xxx,contauner,true); return v; }
解决办法
1. 参数 true 改为 false
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View =inflater.inflate(R.layout.xxx,contauner,false); return v; }
2改用另外一个方法参数
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View =inflater.inflate(R.layout.xxx,null); return v; }