2017-09-15 32 views
1

Java code我如何創建一個自定義ListView與我的XML佈局文件?

list view layout #1

我怎樣才能插入改變我的ListView添加此佈局文件到我的列表視圖的圖形?我應該在我的java代碼中編寫我的ListView的每一行,就像我的佈局文件一樣。謝謝大家!

+0

問題是一點點cofusing,但如果我理解正確的,你必須創建一個自定義適配器和膨脹你的佈局。 – Yupi

+0

是的你是對的,抱歉我的誤解 –

+0

我該怎麼做? –

回答

1

所有你需要創建XML你想要的自定義行(custom_row.xml)首先:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="8dp" 
    android:id="@+id/text" /> </LinearLayout> 

然後你需要創建自定義適配器:

public class CustomAdapter extends BaseAdapter { 
Context context; 
List<String> textArray; 
LayoutInflater inflater; 

public RutinaAdapter(Context context, List<String> textarray) { 
    this.context = context; 
    inflater = LayoutInflater.from(context); 
    this.textArray = textarray; 

} 

@Override 
public int getCount() { 
    return textArray.size(); 
} 

@Override 
public Object getItem(int position) { 
    return textArray.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ViewGroup vg; 

    if (convertView != null) { 
     vg = (ViewGroup) convertView; 
    } else { 
     vg = (ViewGroup) inflater.inflate(R.layout.custom_row, null); 
    } 

    String text = textArray.get(position); 

    final TextView text = ((TextView) vg.findViewById(R.id.text)); 

    return vg; 
} } 

然後你需要將適配器添加到ListView:

list = (ListView) view.findViewById(R.id.list); 
CustomAdapter adapter = new CustomAdapter(getContext(),textArray); 
list.setAdapter(adapter1); 

添加信息到你textArray,並通知adapte數據改變了,就是這樣。

相關問題