2011-04-12 50 views
3

我学习机器人编程,我能够创建一个自定义的ListView 有:如何使用“extends Activity”创建自定义ListView?

public class project1 extends ListActivity 
{ 
.... 
} 

随着自定义布局的XML文件。 我想知道如何做同样的事情,但与

public class project1 extends Activity 

    { 
    .... 
    } 

所有我看着使用extends ListActivity教程,我知道它的存在,以 使事情变得更简单,但对学习的缘故怎么办这是困难的方式?

+1

请务必阅读Java的[命名约定](http://www.oracle.com/technetwork/java/codeconventions-135099.html#367),因为您似乎还不了解它们。 – 2011-04-12 09:13:12

+0

看看这个教程 - http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/ – rajath 2011-04-12 08:59:31

回答

5

看看本教程。 http://techdroid.kbeanie.com/2009/07/custom-listview-for-android.html

查看此帖子。它是先进的一些东西:Lazy load of images in ListView

编辑根据您的评论:

考虑例子显示国家及其缩写名称的列表

首先自定义的ListView,你必须创建一个表示XML文件您的列表视图:

<?xml version="1.0" encoding="utf-8"?> 
<!--main.xml--> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="#ffccd0" 
> 
    <TextView 
     android:text="Countries List" 
     android:textColor="#b3000d" 
     android:gravity="center_vertical|center_horizontal" 
     android:textSize="26dip" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textStyle="bold" 
     android:background="#ffb0b6" 
     android:layout_marginBottom="5dip" 
     android:typeface="sans"/> 
<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="#570000"> 
    <TextView android:id="@+id/tv_1" 
     android:textColor="#FFFFFF" 
     android:gravity="center_vertical|left" 
     android:textSize="16dip" 
     android:layout_height="wrap_content" 
     android:textStyle="bold" 
     android:typeface="serif" 
     android:layout_width="70dip" 
     android:paddingLeft="20dip" 
     android:text="Abbr"> 
    </TextView> 
    <TextView android:id="@+id/tv_2" 
     android:textColor="#FFFFFF" 
     android:gravity="center_vertical|left" 
     android:textSize="16dip" 
     android:layout_height="wrap_content" 
     android:textStyle="bold" 
     android:typeface="serif" 
     android:layout_width="200dip" 
     android:layout_toRightOf="@+id/tv_1" 
     android:text="Countries"> 
    </TextView> 

</RelativeLayout> 
<ListView 
    android:id="@+id/lv_country" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:cacheColorHint="#00000000"> 
</ListView> 
</LinearLayout> 

现在您必须创建一个表示一行列表项的xml文件。 这是我row.xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_height="wrap_content" 
android:gravity="left|center" 
android:layout_width="wrap_content" 
android:paddingBottom="10px" 
android:paddingTop="10px" 
android:paddingLeft="3px"> 
<TextView 
    android:id="@+id/TextView01" 
    android:layout_width="70dip" 
    android:scrollHorizontally="true" 
    android:layout_height="wrap_content" 
    android:gravity="left" 
    android:layout_weight="1" 
    android:singleLine="true" 
    android:textSize="15dip" 
    android:textStyle="bold" 
    android:textColor="#d08021" 
    android:paddingLeft="20dip"> 
</TextView> 
<TextView 
    android:id="@+id/TextView02" 
    android:layout_weight="2" 
    android:layout_width="200dip" 
    android:scrollHorizontally="true" 
    android:layout_height="wrap_content" 
    android:gravity="left" 
    android:singleLine="true" 
    android:layout_marginLeft="10dip" 
    android:textSize="15dip" 
    android:textStyle="bold" 
    android:textColor="#7f0000"> 
</TextView> 
</LinearLayout> 

当你想显示在ListView的字符串数组,我已经使用字符串的静态数组,并存储在CountriesList.java文件。

这是我CountriesList.java文件:

public class CountriesList { 
public static String[] countries = { "Afghanistan", "Albania Albania Albania AlbaniaAlbaniaAlbaniaAlbania Albania ", "Algeria", 
     "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", 
     "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", 
     "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", 
     "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", 
     "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", 
     "Botswana", "Bouvet Island", "Brazil", 
     "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", 
     "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", 
     "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", 
     "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", 
     "Colombia", "Comoros", "Congo", 
     "Congo, the Democratic Republic of the", "Cook Islands", 
     "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus", 
     "Czech Republic", "Denmark", "Djibouti", "Dominica", 
     "Dominican Republic", "Ecuador", "Egypt", "El Salvador", 
     "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", 
     "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", 
     "France", "French Guiana", "French Polynesia", 
     "French Southern Territories", "Gabon", "Gambia", "Georgia", 
     "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", 
     "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", 
     "Guyana", "Haiti", "Heard Island and Mcdonald Islands", 
     "Holy See (Vatican City State)", "Honduras", "Hong Kong", 
     "Hungary", "Iceland", "India", "Indonesia", 
     "Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy", 
     "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", 
     "Korea, Democratic People's Republic of", "Korea, Republic of", 
     "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", 
     "Latvia", "Lebanon", "Lesotho", "Liberia", 
     "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", 
     "Luxembourg", "Macao", 
     "Macedonia, the Former Yugoslav Republic of", "Madagascar", 
     "Malawi", "Malaysia", "Maldives", "Mali", "Malta", 
     "Marshall Islands", "Martinique", "Mauritania", "Mauritius", 
     "Mayotte", "Mexico", "Micronesia, Federated States of", 
     "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", 
     "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", 
     "Netherlands", "Netherlands Antilles", "New Caledonia", 
     "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", 
     "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", 
     "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama", 
     "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", 
     "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", 
     "Russian Federation", "Rwanda", "Saint Helena", 
     "Saint Kitts and Nevis", "Saint Lucia", 
     "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", 
     "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", 
     "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", 
     "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", 
     "South Africa", "South Georgia and the South Sandwich Islands", 
     "Spain", "Sri Lanka", "Sudan", "Suriname", 
     "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", 
     "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", 
     "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo", 
     "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", 
     "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", 
     "Ukraine", "United Arab Emirates", "United Kingdom", 
     "United States", "United States Minor Outlying Islands", "Uruguay", 
     "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", 
     "Virgin Islands, British", "Virgin Islands, U.s.", 
     "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", 
     "Zimbabwe" }; 
public static String[] abbreviations = { "AF Western Sahara Western SaharaWestern Sahara Western SaharaWestern Sahara", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", 
     "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", 
     "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", 
     "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", 
     "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", 
     "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", 
     "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", 
     "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", 
     "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", 
     "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP", 
     "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", 
     "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", 
     "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", 
     "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN", 
     "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", 
     "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", 
     "QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS", 
     "SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB", 
     "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", 
     "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", 
     "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", 
     "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" }; 
} 

当你正在定制的ListView,你必须创建扩展BaseAdapter另一个类,作为工作的ListView的控制器。

因此,这里是我的EfficientAdapter.java文件:

private static class EfficientAdapter extends BaseAdapter { 
    private LayoutInflater mInflater; 

    public EfficientAdapter(Context context) { 
     mInflater = LayoutInflater.from(context); 
    } 

    public int getCount() { 
     return CountriesList.abbreviations.length; 
    } 

    public Object getItem(int position) { 
     return position; 
    } 

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

    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.row, null); 
      holder = new ViewHolder(); 
      holder.text1 = (TextView) convertView 
        .findViewById(R.id.TextView01); 
      holder.text2 = (TextView) convertView 
        .findViewById(R.id.TextView02); 

      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     holder.text1.setText(CountriesList.abbreviations[position]); 
     holder.text2.setText(CountriesList.countries[position]); 

     return convertView; 
    } 

    static class ViewHolder { 
     TextView text1; 
     TextView text2; 
    } 
} 

现在剩下的最后一件事是你的活动课。 这就是:

public class MyList extends Activity { 
/** Called when the activity is first created. */ 
ListView listView; 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    listView = (ListView) findViewById(R.id.lv_country); 
    listView.setAdapter(new EfficientAdapter(this)); 

      listView.setOnItemClickListener(  
      new OnItemClickListener() 
      { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) { 
        // TODO Auto-generated method stub 
        Toast.makeText(getApplicationContext(),"You Selected Item "+Integer.toString(position), Toast.LENGTH_LONG).show();   
       }  
      } 
    ); 
} 
+0

在第一个链接的源代码中,我如何填充列表使用现有的字符串数组, – Deepak 2011-04-12 16:20:35

+0

谢谢你,现在我明白发生了什么,以及如何通过扩展ListActivity简化代码。 – Deepak 2011-04-13 06:00:02

+0

最受欢迎:) :) – 2011-04-13 06:00:46

2

这是不是真的任何事情扩展Activity时更难。

唯一发生变化的是您首先必须使用findViewById()方法获取对XML布局文件中定义的ListView的引用。

ListView mListView = (ListView)findViewById(R.id.my_listview); 

定义自定义Adapter的工作原理是一样的。只需创建它并分配您的ListView该适配器。

mListView.setAdapter(mAdapter); 

那就是它。没什么特别的。

-2
public class ListViewLoader extends ListActivity 
     implements LoaderManager.LoaderCallbacks<Cursor> { 

    // This is the Adapter being used to display the list's data 
    SimpleCursorAdapter mAdapter; 

    // These are the Contacts rows that we will retrieve 
    static final String[] PROJECTION = new String[] {ContactsContract.Data._ID, 
      ContactsContract.Data.DISPLAY_NAME}; 

    // This is the select criteria 
    static final String SELECTION = "((" + 
      ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" + 
      ContactsContract.Data.DISPLAY_NAME + " != ''))"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Create a progress bar to display while the list loads 
     ProgressBar progressBar = new ProgressBar(this); 
     progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
       LayoutParams.WRAP_CONTENT, Gravity.CENTER)); 
     progressBar.setIndeterminate(true); 
     getListView().setEmptyView(progressBar); 

     // Must add the progress bar to the root of the layout 
     ViewGroup root = (ViewGroup) findViewById(android.R.id.content); 
     root.addView(progressBar); 

     // For the cursor adapter, specify which columns go into which views 
     String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME}; 
     int[] toViews = {android.R.id.text1}; // The TextView in simple_list_item_1 

     // Create an empty adapter we will use to display the loaded data. 
     // We pass null for the cursor, then update it in onLoadFinished() 
     mAdapter = new SimpleCursorAdapter(this, 
       android.R.layout.simple_list_item_1, null, 
       fromColumns, toViews, 0); 
     setListAdapter(mAdapter); 

     // Prepare the loader. Either re-connect with an existing one, 
     // or start a new one. 
     getLoaderManager().initLoader(0, null, this); 
    } 

    // Called when a new Loader needs to be created 
    public Loader<Cursor> onCreateLoader(int id, Bundle args) { 
     // Now create and return a CursorLoader that will take care of 
     // creating a Cursor for the data being displayed. 
     return new CursorLoader(this, ContactsContract.Data.CONTENT_URI, 
       PROJECTION, SELECTION, null, null); 
    } 

    // Called when a previously created loader has finished loading 
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) { 
     // Swap the new cursor in. (The framework will take care of closing the 
     // old cursor once we return.) 
     mAdapter.swapCursor(data); 
    } 

    // Called when a previously created loader is reset, making the data unavailable 
    public void onLoaderReset(Loader<Cursor> loader) { 
     // This is called when the last Cursor provided to onLoadFinished() 
     // above is about to be closed. We need to make sure we are no 
     // longer using it. 
     mAdapter.swapCursor(null); 
    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     // Do something when a list item is clicked 
    } 
} 
+1

这个问题明确要求一种方式来做*没有*扩展ListActivity – miniBill 2012-07-14 16:13:57