一.概述
有時項目需要動態設置一個 底部列表,比如 popupwindow ,listview 底部顯示 ,所以記錄一下
此處,
android.support.v7.widget.CardView 中包含了一個listview,而我要實現的是, 點擊mLayout這個布局上面的 6個按鈕, 在底部彈出不同的listview. 項目中
mLayout是一個 LinearLayout
二.代碼如下
View view = View.inflate(getActivity(),R.layout.template_listview,null); cardView = (CardView) view.findViewById(R.id.cardView); cardView.setVisibility(View.GONE); listView = (ListView) view.findViewById(R.id.listView); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.BOTTOM; cardView.setLayoutParams(params); mLayout.addView(cardView);
發現
params.gravity = Gravity.BOTTOM; 根本就不起作用,原來 主布局 mlayout 我定義成了 垂直的,定義成 水平布局就好了.
當 android:orientation="vertical" 時, 只有水平方向的設置才起作用,垂直方向的設置不起作用。即:left,right,center_horizontal 是生效的。
當 android:orientation="horizontal" 時, 只有垂直方向的設置才起作用,水平方向的設置不起作用。即:top,bottom,center_vertical 是生效的。
如果mLayout 是一個 相對布局,而我們想把這個 cardView 控件顯示到 相對布局底部,可以這么寫
View view = View.inflate(getActivity(),R.layout.template_listview,null); cardView = (CardView) view.findViewById(R.id.cardView); cardView.setVisibility(View.GONE); listView = (ListView) view.findViewById(R.id.listView); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); cardView.setLayoutParams(params); mLayout.addView(cardView);