1. 程式人生 > >D.K.的Android旅程----BaseAdapter實現ListView

D.K.的Android旅程----BaseAdapter實現ListView

上一篇部落格是寫的SimpleAdapter實現ListView.

接下來介紹的是BaseAdapter實現ListView.

BaseAdapter對開發者而言擁有更大的可控性.開發者可控制列表的每一項.

XML:

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   xmlns:tools="http://schemas.android.com/tools"

   android:layout_width="match_parent"

   android:layout_height="match_parent" >

    <ListView

        android:id="@+id/listview"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

         />

</LinearLayout>

Java:

publicclass MainActivity extends Activity {

    @Override

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ListView listview = (ListView)findViewById(R.id.listview);

           BaseAdapter adapter = newBaseAdapter()

           {

                  public int getCount()

                  {

                         // 指定一共包含40個選項

                         return 40;

                  }

                  public Object getItem(intposition)

                  {

                         return null;

                  }

                  // 重寫該方法,該方法的返回值將作為列表項的ID

                  public long getItemId(intposition)

                  {

                         return position;

                  }

                  // 重寫該方法,該方法返回的View將作為列表框

                  public View getView(intposition

                                , ViewconvertView , ViewGroup parent)

                  {

                         // 建立一個LinearLayout,並向其中新增2個元件

                         LinearLayout line = newLinearLayout(MainActivity.this);

                         line.setOrientation(0);

                         ImageView image = newImageView(MainActivity.this);

                         image.setImageResource(R.drawable.ic_launcher);

                         TextView text = newTextView(MainActivity.this);

                         text.setText("第"+ (position +1 ) + "個列表項");

                         line.addView(image);

                         line.addView(text);

                         // 返回LinearLayout例項

                         return line;

                  }

           };

        listview.setAdapter(adapter) ;

    }

}

BaseAdapter的四個需覆寫的方法:getCount()、getItem(intpositon)、getItemId(int positon)、getView(intposition, View convertView , ViewGroup parent).

這四個方法決定的列表中每一項的內容。

所以在android開發中,如果要實現複雜且是自己想要實現的列表項,用BaseAdapter最佳.