2016-04-26 23 views
0

我需要創建LinearLayout,它具有ListView。listView項不匹配父項n線性佈局

this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 
    final ListView listView = (ListView) LayoutInflater.from(getContext()).inflate(R.layout.chat_timer_rollout, null); 
    addView(listView); 

我的聊天計時器部署是:我這個代碼做了

final ArrayAdapter<TimeInterval> adapter = new ArrayAdapter<>(getContext(), 
                   R.layout.chat_timer_item, 
                   R.id.timer_label, TimeInterval.INTERVALS); 

    listView.setAdapter(adapter); 

<ListView 
xmlns:a="http://schemas.android.com/apk/res/android" 
a:layout_width="match_parent" 
a:layout_height="wrap_content" 
a:background="@color/white" 
a:cacheColorHint="@color/white" 
a:paddingBottom="12dp" 
a:paddingTop="12dp"> 

創建我一直在努力,在列表視圖中添加項目,如在此之後

聊天定時器項目有代碼:

<TextView 
a:id="@+id/timer_label" 
xmlns:a="http://schemas.android.com/apk/res/android" 
a:layout_width="match_parent" 
a:layout_height="wrap_content" 
a:paddingBottom="11dp" 
a:paddingLeft="@dimen/timer_label_margin_right" 
a:paddingTop="11dp" 
a:textColor="@color/primary_text" 
a:textSize="@dimen/timer_text_size"/> 

創建這個後,我看到我的屏幕上的線性佈局,但是當我點擊項目它有寬度wrap_content,不匹配父?如何解決它?我試圖設置一個更多的線性佈局用參數match_parent膨脹,但它沒有幫助。謝謝!

+1

將'inflate()'調用中的第二個參數更改爲'this',並移除addView()調用。 –

+0

@ MikeM.非常感謝 –

回答

1

LayoutInflater#inflate()方法中的第二個參數是膨脹版式的(可選)父View。當您通過父母的null時,Inflater不知道哪種類型的LayoutParams是合適的,因此它使用默認ViewGroup.LayoutParams,其中兩個維度都有ViewGroup.WRAP_CONTENT

由於您的發佈代碼位於您的LinearLayout子類中,因此您可以將this作爲inflate()調用的第二個參數。此外,當您在該雙參數方法中提供父母View時,自動添加了虛擬佈局,因此您不需要撥打addView()

final ListView listView = (ListView) LayoutInflater.from(getContext()) 
    .inflate(R.layout.chat_timer_rollout, this);