2016-08-01 80 views

回答

1

該代碼看起來不太難看,但是在瞭解之後,您可以按照自己喜歡的方式進行操作。

1)用你想要顯示的方式用TextView創建一個Layout。 例如/res/layout/item_layout.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="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Large Text" 
    android:id="@+id/text_view_at_custom_layout" 
    android:layout_gravity="center_horizontal"/> 

PS:請注意,我用

android:gravity="center" 

2)創建與您的數據列表(在這種情況下字符串)

String strs[] = {"Good","Bag","Cute","Ugly","Hot","Cold","ETC"}; 
// mList i declare it global to use it on the inner class 
mList = Arrays.asList(strs); 

3)創建一個擴展ArrayAdapter的類 我做了一個內部類wi默認構造函數注意哪些參數傳遞給super();

private class MyCustomAdapter extends ArrayAdapter<String> 
{ 
    public MyCustomAdapter() 
    { 
     super(MainActivity.this,R.layout.item_layout,mList); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) 
    { 
     if(convertView==null) convertView = getLayoutInflater().inflate(R.layout.item_layout,parent,false); 

     TextView textViewAtCustomLayout = (TextView)convertView.findViewById(R.id.text_view_at_custom_layout); 
     textViewAtCustomLayout.setText(mList.get(position)); 

     return convertView; 
    } 

4)現在將適配器設置爲你的ListView

listView.setAdapter(new MyCustomAdapter()); 

,如果你不喜歡默認的構造函數,你可以創建帶有參數的構造函數,並在這裏傳遞。

這裏是完整的代碼

https://github.com/adliano/SimpleListView

,這是怎麼看起來像

screenshot_simple_listview

我希望這會有所幫助!