ArrayAdapter使用

ArrayAdapter将数组中的每个元素绑定到布局资源中定义的简单View控件。

1.定义textview.xml

<?xml version=”1.0″ encoding=”utf-8″?>
   
<TextView
    xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”fill_parent”
    android:layout_height=”wrap_content”
    android:textSize=”20sp” />

2.定义界面

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

    <TextView
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”@string/main_menu” 
        android:textSize=”30sp”/>
    
    <ListView android:id=“@android:id/list”
        android:layout_width=”fill_parent”
        android:layout_height=”0dip”
        android:layout_weight=”1″
        android:drawSelectorOnTop=”false”/>

</LinearLayout>

3.在代码中加载数据源及点击事件

package com.introtoandroid.advancedlayouts;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MyListActivity extends ListActivity {

private String[] items= { “Basic Layout”, 
“List Layout”, 
“Grid View” };
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_layout);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.textview, items));
    }

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.d (AdvancedLayoutsActivity.DEBUG_TAG, “pos: “+position + ” , id: “+ id);
switch (position) {
case 0:
Intent intent = new Intent(this,
BasicLayoutActivity.class);
startActivity(intent);
break;
case 1:
TextView tv = (TextView) v;
tv.setText(“Changed”);
break;
case 2:
String original = (String) l
.getItemAtPosition(position);
Log.d(AdvancedLayoutsActivity.DEBUG_TAG, “original string: “
+ original);
((TextView) v).setText(“Updated”);
break;
}
}
}

发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *