2016-10-30 119 views
0

如何更改列表視圖中顯示的行數?更改列表視圖中的行數

enter image description here

我想顯示在ListView三個項目,然後有它可滾動。 我知道我可以硬編碼列表視圖的高度,但有沒有更好的方式做到這一點?

回答

0

您可以在添加行後獲取行的高度,然後將listview的高度更改爲3 * height。您需要在列表呈現後執行所有這些操作。

例如:

ListView listView = (ListView) findViewById(R.id.listView); 
    String[] names = new String[] {"hi", "my", "name", "is", "slim", "shady"}; 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, names); 
    listView.setAdapter(adapter); 
    View row = listView.getAdapter().getView(0, null, listView); 
    row.measure(0, 0); 
    int rowHeight = row.getMeasuredHeight(); 
    listView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rowHeight*3)); 
+0

我嘗試已經 'INT高度= 3 *(LayoutInflater.from(mContext).inflate(R.layout.review_list_item,NULL))的getHeight(); listView.setMinimumHeight(height);' 但它沒有工作。我不知道爲什麼 –

+0

你需要檢查列表呈現後的高度: 查看行= listView.getAdapter()。getView(0,null,listView); row.measure(0,0); int rowHeight = row.getMeasuredHeight(); (新的RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,rowHeight * 3)); –

+0

定義了一個自定義的行,用於擴展listView,在自定義行中定義視圖組小部件,如:TextView,TmageView,EditText。然後設置行的高度來包裝內容,這將有助於解決這個需求。 你也可以[看本教程](http://blog.lovelyhq.com/setting-listview-height-depending-on-the-items/) –