Android移动应用开发——第二章 programming for listview

本文详细介绍了如何在Android应用中使用自定义适配器,包括Spinner、ListView和GridView的实现。从创建ArrayAdapter到自定义View,再到处理事件,展示了在不同场景下适配器的灵活运用,涵盖了颜色选择、尺寸变化和图片显示等交互功能。同时,还涉及了数据结构如ArrayList和HashMap的使用,以及自定义类和数据绑定。
摘要由CSDN通过智能技术生成

Task 2-1

题目
Write an app like Spinner-task1 with 2 Textviews and 1 Spinner. The 1st TextView shows your name and sutdent number. The 2nd TextView shows the selected message of the Spinner.

  1. Set three city names in the xml file by tag;
  2. Define a layout with one Spinner and one TextView
  3. Get the city names in java code
  4. Give the city names to the Spinner
  5. The TextView’s text changes according to the city name selected by Spinner

演示
在这里插入图片描述

分析步骤
1、ArrayAdapter
在这里插入图片描述例:创建ArrayAdapter练习
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
2、构造数据:使用getResources().getStringArray()获取res/string.xml中添加的name 为city_name 的string_array
在这里插入图片描述
3、将适配器绑定到spinner控件上,并设置监听

代码

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_spinner);
        Spinner sp = findViewById(R.id.sp);
        Resources res = getResources();
        final String[] array = res.getStringArray(R.array.city_name);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
        sp.setAdapter(adapter);
        final TextView tv= findViewById(R.id.tv);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = array[position];
                tv.setText(item);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
}

Task 2-2

题目
Write an app like Spinner-task2 with 1 Textview and 1 Spinner. The TextView shows your name and sutdent number.

  1. Define 3 colors in colors.xml ( red, blue and green)
  2. Define a color array in the colors.xml
  3. Get the color array in java code
  4. Define a string array for the names of the three colors
  5. Set the string array to a Spinner by ArrayAdapter
  6. Set the selecting events for the Spinner to change the text color of the TextView

演示
在这里插入图片描述

分析步骤
类似Task 2-1的操作,此处补充:
如果是string-array和integer-array的话。可以直接get对应的array
在这里插入图片描述
如果是array类型的话,我们需要先用obtainTypedArray获得一个TypedArray,然后使用typedarray中的getcolor来获得里面的数据
注意:需要传两个参数,一个是位置position,还有一个是默认颜色,在读取失败的时候使用
在这里插入图片描述

代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_spinner);
        Spinner sp = findViewById(R.id.sp);
        final TextView tv = findViewById(R.id.tv);
        Resources res = getResources();
        final TypedArray typedArray = res.obtainTypedArray(R.array.myColor);
        String[] colorNames = res.getStringArray(R.array.colorNames);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,colorNames);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int color = typedArray.getColor(position, Color.BLUE);
                tv.setTextColor(color);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
}

Task 2-3

题目
Write an app like Spinner-task3 with 1 Textview and 1 Spinner. The TextView shows your name and sutdent number.

  1. Define 3 dimensions in dimens.xml (small, medium and big, [12sp, 16sp, 20sp])
  2. Define a dimension array in the dimens.xml
  3. Get the dimension array in java code
  4. Define a string array for the names of the three dimensions
  5. Set the string array to a Spinner by ArrayAdapter
  6. Set the selecting events for the Spinner to change the text dimension of the TextView

演示
在这里插入图片描述

分析步骤
1、在values文件夹下新增一个dimen.xml用来设置字体大小
2、其他同task 2-2
代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_spinner);
        Spinner sp = findViewById(R.id.sp);
        final TextView tv = findViewById(R.id.tv);
        Resources res = getResources();
        final TypedArray typedArray = res.obtainTypedArray(R.array.myDimens);
        String[] myDiemensName = res.getStringArray(R.array.myDimensNames);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,myDiemensName);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                float dimension = typedArray.getDimension(position, 10.0f);
                tv.setTextSize(dimension);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

Task2-4

题目:

Write an app like ListView-task1 with 1 Textview , 1 ImageView and 1 ListView. The TextView shows your name and sutdent number.

  1. Copy 3 pictures to the fold res/drawable
  2. Define a string array or arraylist for the names of the pictures
  3. Add an ImageView to the layout xml with center gravity and 200dp width and height
  4. Add a ListView to the layout xml
  5. Create an ArrayAdapter for the names of the pictures
  6. Set the selecting events for the Spinner to change the text dimension of the TextView
  7. Set the ArrayAdapter to the ListView
  8. The ImageView changes the picture when users click the ListView
  9. The first item of the listview is your hometown

演示:
在这里插入图片描述

分析与步骤
1、添加listview组件,构建数据,绑定适配器,并绑定到listview中
在这里插入图片描述2、设置侦听事件,当listview中的item被点击时触发OnItemClickListener
在这里插入图片描述
在这里插入图片描述3、如何获取listview中被点击的item的具体位置
在这里插入图片描述4、修改imageView中的图片:setImageResource(int id)来改变图片

代码

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_main);
        final String[] data={"Hangzhou","Wenzhou","Shanghai"};
        final int[] picId= new int[]{R.drawable.hangzhou, R.drawable.wenzhou, R.drawable.shanghai};
        ListView lv =findViewById(R.id.listview);
        final ImageView iv=findViewById(R.id.imageView);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s = data[position];
                iv.setImageResource(picId[position]);
                Toast.makeText(MainActivity.this,s, LENGTH_SHORT).show();
            }
        });

    }
}

Task 2-5

题目:
Write an app like SimpleAdapter-task1 with 1 Textview and 1 ListView. The TextView shows your name and sutdent number.

  1. Develop a contact app for superstar
  2. The row view of the ListView contains
    [1] 1 ImageView on the left side with 100dp width and height
    [2] Two TextViews vertically layouted: 1 TextView for name with 24 sp text size; 1 TextView for phone number with default size
    [3] 1 ImageView for call button with 40dp width and height
  3. A Toast shows the name when users click the item of the ListView
    Hints: the data for the SimpleAdapter is contructed by ArrayList with HashMap data, the key string for the HashMap can be defined by public static final field variables. The layout for the SimpleAdapter is customized.

演示
在这里插入图片描述

分析与步骤
1、SimpleAdapter
在这里插入图片描述

代码

public class MainActivity extends AppCompatActivity {
    public static final String KEY_PHONE="key_phone";
    public static final String KEY_NAME="key_name";
    public static final String KEY_PIC_ID="key_pic_id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_main);
        ListView lv = findViewById(R.id.listview);
        String[] phone={"11111","22222","333333"};
        String[] name = {"hangzhou","shanghai","wenzhou"};
        int [] picid=new int[]{R.drawable.hangzhou,R.drawable.shanghai,R.drawable.wenzhou};
        final ArrayList<HashMap<String,Object>> list = new ArrayList<>();
        for (int i = 0; i <name.length ; i++) {
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put(KEY_PHONE,phone[i]);
            hashMap.put(KEY_NAME,name[i]);
            hashMap.put(KEY_PIC_ID,picid[i]);
            list.add(hashMap);
        }
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.row_view,new String[]{KEY_PHONE,KEY_NAME,KEY_PIC_ID},
                new int[]{R.id.tv_phone,R.id.tv_name,R.id.imageView});
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,Object> hashMap = list.get(position);
                Toast.makeText(MainActivity.this,hashMap.get(KEY_PHONE).toString(), LENGTH_SHORT).show();
            }
        });
    }
}

Task 2-6

题目
Write an app like OverrideAdapter-task1 with 1 Textview and 1 ListView. The TextView shows your name and sutdent number.

  1. Develop a contact app for superstar
  2. The row view of the ListView contains
    [1] 1 ImageView on the left side with 100dp width and height
    [2] Two TextViews vertically layouted: 1 TextView for name with 24 sp text size; 1 TextView for phone number with default size
    [3] 1 ImageView for call button with 40dp width and height
  3. If the length of phone number is less than 1, the call ImageView is invisible
  4. A Toast shows the name when users click the item of the ListView
  5. A Toast shows the calling number when users click the call ImageView
    Hints: the data for the superstar is contructed by a customized class (like PhoneData), and the adapter is extended from ArrayAdapter which is suitable for the user defined class data.
    演示
    在这里插入图片描述

分析与步骤
1、自定义适配器:重写getView方法
在这里插入图片描述2、使用view.findviewbyid来获得该布局内的控件
3、通过setVisibility(View.GONE)来设置图片不可见
4、通过iv.setImageResource(phoneData.getId());来改变图片
5、判断字符串为空:TextUtils.isEmpty(phoneData.getPhone())

代码
MainActivity

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity {
    public static final String KEY_PHONE="key_phone";
    public static final String KEY_NAME="key_name";
    public static final String KEY_PIC_ID="key_pic_id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_main);
        ListView lv = findViewById(R.id.listview);
        final ArrayList<PhoneData> list = new ArrayList<>();
        list.add(new PhoneData("hangzhou","111111",R.drawable.hangzhou));
        list.add(new PhoneData("wenzhou","2222222",R.drawable.wenzhou));
        list.add(new PhoneData("shanghai","3333333",R.drawable.shanghai));
        PhoneDataAdapter adapter = new PhoneDataAdapter(MainActivity.this,list);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PhoneData phoneData = list.get(position);
                Toast.makeText(MainActivity.this,phoneData.getName(), LENGTH_SHORT).show();
            }
        });
    }
}

PhoneDataAdapter

public class PhoneDataAdapter extends ArrayAdapter {
    private Context context;
    private ArrayList<PhoneData> list;
    public PhoneDataAdapter(@NonNull Context context,ArrayList<PhoneData> list) {
        super(context, android.R.layout.simple_list_item_1,list);
        this.context=context;
        this.list=list;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v = LayoutInflater.from(context).inflate(R.layout.row_view,null,false);
        ImageView iv = v.findViewById(R.id.imageView);
        ImageView iv_call = v.findViewById(R.id.iv_call);
        TextView tv_phone = v.findViewById(R.id.tv_phone);
        TextView tv_name = v.findViewById(R.id.tv_name);
        final PhoneData phoneData = list.get(position);
        tv_name.setText(phoneData.getName());
        tv_phone.setText(phoneData.getPhone());
        iv.setImageResource(phoneData.getId());
        if (TextUtils.isEmpty(phoneData.getPhone())){
            iv_call.setVisibility(View.GONE);
        }
        iv_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,phoneData.getPhone(),Toast.LENGTH_SHORT).show();
            }
        });
        return v;
    }
}

Task 2-7 GridView初体验

题目
Write an app like GridView-task1 with 2 Textviews , and 1 GridView. The first TextView shows your name and student number. The second TextView shows the clicked item of the GridView. The GridView shows 99 string items in 3 columns. The 99 strings are generated and stored in ArrayList.
演示
在这里插入图片描述
分析与步骤
1、GridView的参数

  • columnWidth
  • gravity
  • horizontalSpacing / verticalSpacing水平间,垂直间的距离
  • numColumns:设置列数,可以是具体的数字,也可以为auto_fit
  • stretchMode生长模式
    在这里插入图片描述代码
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_main);
        GridView gv =findViewById(R.id.gv);
        final ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i <50 ; i++) {
            String s = String.format("Item%02d",i);
            list.add(s);
        }
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s = list.get(position);
                Toast.makeText(MainActivity.this, s, LENGTH_SHORT).show();
            }
        });
    }
}

Task2-8 GridView进阶

题目
Write an app like GridView-task2 with 1 Textview , and 1 GridView. The first TextView shows your name and student number. The GridView shows landscapes in 2 column
[1] The item in the GridView includes one ImageView and one TextView (under the ImageView)
[2] The landscapes are described by ArrayList with customized class Landscape
[3] The Adapter is customized by override ArrayAdapter

演示
在这里插入图片描述

分析与步骤
1、适配器的改写
2、GridView的使用
代码
MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_main);
        GridView gv =findViewById(R.id.gv);
        final ArrayList<landscape> list = new ArrayList<>();
        for (int i = 0; i <50 ; i++) {
            list.add(new landscape("hangzhou",R.drawable.hangzhou));
            list.add(new landscape("shanghai",R.drawable.shanghai));
            list.add(new landscape("wenzhou",R.drawable.wenzhou));
        }
        LandscapeAdapter adapter = new LandscapeAdapter(MainActivity.this,list);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               landscape landscape = list.get(position);
               Toast.makeText(MainActivity.this,landscape.getName().toString(),Toast.LENGTH_SHORT).show();
           }
       });
    }
}

LandscapeAdapter

public class LandscapeAdapter extends ArrayAdapter {
    private Context context;
    private ArrayList<landscape> list;
    public LandscapeAdapter(@NonNull Context context,ArrayList<landscape> list) {
        super(context,android.R.layout.simple_list_item_1,list);
        this.context=context;
        this.list=list;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v = LayoutInflater.from(context).inflate(R.layout.test_gridview_adapter,null,false);
        ImageView iv = v.findViewById(R.id.img);
        TextView tv = v.findViewById(R.id.tv_landscape);
        landscape landscape = list.get(position);
        iv.setImageResource(landscape.getId());
        tv.setText(landscape.getName());

        return v;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值