赞
踩
我们实现一个简单的商品展示界面
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/good_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="333dp" android:layout_marginTop="32dp" android:text="TextView" /> <TextView android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="92dp" android:layout_marginTop="32dp" android:text="商品名称:" /> <TextView android:id="@+id/good_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:text="TextView" /> <TextView android:id="@+id/textView9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_marginTop="32dp" android:layout_marginEnd="101dp" android:text="商品价格:" /> <ImageView android:id="@+id/imageView2" android:layout_width="86dp" android:layout_height="86dp" tools:srcCompat="@tools:sample/avatars" /> </RelativeLayout>
创建一个Bean来存储每一个item的展示数据
package com.example.androidtest.Adapter.BaseAdapter; public class GoodData { private Integer imgId; private String good_name; private Double good_price; public void set(Integer imgId, String good_name, Double good_price) { this.imgId = imgId; this.good_name = good_name; this.good_price = good_price; } @Override public String toString() { return "GoodData{" + "imgId=" + imgId + ", good_name='" + good_name + '\'' + ", good_price=" + good_price + '}'; } public Integer getImgId() { return imgId; } public void setImgId(Integer imgId) { this.imgId = imgId; } public String getGood_name() { return good_name; } public void setGood_name(String good_name) { this.good_name = good_name; } public Double getGood_price() { return good_price; } public void setGood_price(Double good_price) { this.good_price = good_price; } }
创建一个类继承BaseAdapter,实现他的几个方法
package com.example.androidtest.Adapter.BaseAdapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.androidtest.R; import java.util.List; public class MyBaseAdapter extends BaseAdapter { //创建一个集合来存储数据 private Context context; private List<GoodData> goodDatas; public MyBaseAdapter(List<GoodData> goodDatas,Context context) { this.goodDatas = goodDatas; this.context = context; } //这个方法返回的是绑定的条目数,在这里也就是数据的数量 @Override public int getCount() { return goodDatas.size(); } //获取指定位置的对象 @Override public Object getItem(int position) { return goodDatas.get(position); } //返回指定的id @Override public long getItemId(int position) { return position; } //在这里将数据和view进行绑定 @Override public View getView(int position, View convertView, ViewGroup parent) { //第一个参数是在Activity传过来的context,第二个参数是item的id convertView = View.inflate(context, R.layout.activity_base_adapter_test_item,null); //将组件一一对应 ImageView imageView = convertView.findViewById(R.id.good_image); TextView good_name = convertView.findViewById(R.id.good_name); TextView good_price = convertView.findViewById(R.id.good_price); //将数据放入每一个组件 imageView.setImageResource(goodDatas.get(position).getImgId()); good_name.setText(goodDatas.get(position).getGood_name()); good_price.setText(String.valueOf(goodDatas.get(position).getGood_price())); return convertView; } }
创建Activity页面,并且在Activity里面创建数据,由于Activity界面只需要创建一个ListView即可,此处就不再示范了
package com.example.androidtest.Adapter.BaseAdapter; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import com.example.androidtest.R; import java.util.ArrayList; import java.util.List; public class BaseAdapterTestActivity extends AppCompatActivity { private ListView listView; private int [] imgIds = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher}; private String [] goodNames = {"商品1","商品2","商品3","商品4"}; private double [] goodPrices = {1.11,2.22,3.33,4.44}; private List<GoodData>goodDatas = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_adapter_test); listView = findViewById(R.id.baseAdapterTest); //通过循环将数据组装 for (int i = 0;i<imgIds.length;i++){ GoodData goodData = new GoodData(); goodData.set(imgIds[i],goodNames[i],goodPrices[i]); goodDatas.add(goodData); } //实例化BaseAdapter MyBaseAdapter adapter = new MyBaseAdapter(goodDatas,getApplicationContext()); listView.setAdapter(adapter); } }
展现一个带图片的城市列表,当点击某一城市时,将在列表上方显示该城市名称
创建item的布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageCity" android:layout_width="wrap_content" android:layout_height="98dp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginTop="17dp" tools:srcCompat="@tools:sample/avatars" /> <TextView android:id="@+id/nameCity" android:layout_width="96dp" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="TextView" /> </RelativeLayout>
布局显示为
Activity页面
Activity页面的布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Adapter.SimpleAdapter.SimpleAdapterTestActivity"> <TextView android:id="@+id/cityList" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="城市列表" /> <ListView android:id="@+id/simpleAdapter" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginStart="3dp" android:layout_marginTop="44dp" /> </RelativeLayout>
Activity
package com.example.androidtest.Adapter.SimpleAdapter; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.example.androidtest.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SimpleAdapterTestActivity extends AppCompatActivity { private TextView textView; private ListView listView; private List<Map<String,Object>>data = new ArrayList<>(); private String [] cities = {"北京","上海","广东","深圳"}; private int [] imgs = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_adapter_test); textView = findViewById(R.id.cityList); listView = findViewById(R.id.simpleAdapter); //组装数据 for (int i = 0;i<imgs.length;i++){ Map<String,Object>map = new HashMap<>(); map.put("img",imgs[i]); map.put("name",cities[i]); data.add(map); } //实例化SimpleAdapter SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),data,R.layout.activity_simple_adapter_test_item,new String[]{"img","name"}, new int[]{R.id.imageCity,R.id.nameCity}); listView.setAdapter(adapter); } }
结果
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( ArrayListDemo.this, android.R.layout.simple_list_item_1, adapterData);
程序包含两个 Activity,其中一个 Activity 中包含一个按钮和文本框,按钮内
容为“请选择一个学历”,点击该按钮,弹出另一个 Activity,该 Activity 中显示一个学历列表,选择某一学历后,该学历名称将显示在前一个 Activity 的文本框中
由于此案列布局文件较为简单,这里就不作展示了
第一个Activity
package com.example.androidtest.Adapter.ArrayAdapter; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.androidtest.R; import javax.xml.transform.Result; public class ArrayAdapterFirstActivity extends AppCompatActivity { private Button button; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_array_adapter_first); button = findViewById(R.id.arrayAdapterButton); textView = findViewById(R.id.arrayAdapterTextView); //点击按钮发生跳转 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ArrayAdapterFirstActivity.this, ArrayAdapterSecondActivity.class); //由于要接收返回值,故使用这个方法进行跳转 //但是这样子就要重写onActivityResult startActivityForResult(intent, 1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); //必须满足条件,才接收数据 if (requestCode == 1 && resultCode == RESULT_OK) { textView.setText(data.getStringExtra("academic")); } } }
第二个Activity
package com.example.androidtest.Adapter.ArrayAdapter; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.androidtest.R; public class ArrayAdapterSecondActivity extends AppCompatActivity { private ListView listView; private String [] data = {"小学","中学","高职高专","本科","研究生","博士"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_array_adapter_second); listView = findViewById(R.id.arrayAdapterListView); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,data); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ArrayAdapterSecondActivity.this,ArrayAdapterFirstActivity.class); String academic = data[position]; intent.putExtra("academic",academic); setResult(RESULT_OK,intent); finish(); } }); } }
该类的作用 或者说是目的就是将一个Cursor的所有列分别绑定 到ImageView或者是TextView,你可以选择这个Cursor中你想要显示的列
SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)
SimpleCursorAdapter参数from必须包含_id字段
创建了数据库名称为“Books.db”,其中包含一张表:books 表,其中
存放书籍的基本信息.
书籍的信息随便填写
需要创建一个书籍名称列表界面,然后用户点击选择书籍名,系统打开书籍详细信息界面的应用,要求在一个 Activity 中列表显示书籍名称信息,然后在另一个 Activity 中查询并展示某一个书籍的详细信息
布局文件较为简单,就不作描述了
自定义DBHelper文件来创建表
package com.example.androidtest.Adapter.SimpleCursor; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private int vision = 1; private static final String creat_book = "CREATE TABLE books " + "(_id INTEGER PRIMARY KEY, " + "book_name TEXT, " + "book_isbn TEXT, " + "book_author TEXT, " + "book_press TEXT, " + "book_price NUMBERIC " + "); "; private static final String insert_book1 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('Java 程序设计','0001-9999-0001',' 张力',' 电子工业出版社',36.0)"; private static final String insert_book2 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('Android 权威指南','0001-8888-0001',' 王琦',' 人民出版社',59.0)"; private static final String insert_book3 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('SQLite 数据库应用指南','0001-6666-0001',' 李帅',' 希望出版社',28.0)"; public DBHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } //在这里创建表,插入数据 @Override public void onCreate(SQLiteDatabase db) { db.execSQL(creat_book); db.execSQL(insert_book1); db.execSQL(insert_book2); db.execSQL(insert_book3); } //如果数据库的版本发生变化,在这里进行处理 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table books"); onCreate(db); } }
创建第一个页面
package com.example.androidtest.Adapter.SimpleCursor; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import com.example.androidtest.R; import java.util.HashMap; import java.util.Map; public class SimpleCursorFirstActivity extends AppCompatActivity { private ListView listView; private SQLiteDatabase database; private DBHelper dbHelper; private Map<String,Integer>map = new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_cursor_first); listView = findViewById(R.id.simpleCursorListView1); //实例化DBHelper dbHelper = new DBHelper(getApplicationContext(),"book.db",null,1); //得到SQLiteDatabase database = dbHelper.getWritableDatabase(); String [] columns = {"_id","book_name"}; //执行查询命令,只查询id和name Cursor cursor = database.query("books",columns,null,null,null,null,null); while (cursor.moveToNext()){ //将id和name放入map map.put(cursor.getString(1),cursor.getInt(0)); } SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,cursor,new String[]{"book_name"}, new int[]{android.R.id.text1}); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView textView = (TextView)view; Intent intent = new Intent(SimpleCursorFirstActivity.this,SimpleCursorSecondActivity.class); intent.putExtra("id",String.valueOf(map.get(textView.getText()))); startActivity(intent); } }); } }
第二个页面
package com.example.androidtest.Adapter.SimpleCursor; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.androidtest.R; public class SimpleCursorSecondActivity extends AppCompatActivity { private ListView listView; private SQLiteDatabase database; private DBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_cursor_second); listView = findViewById(R.id.simpleCursorListView2); dbHelper = new DBHelper(getApplicationContext(), "book.db", null, 1); database = dbHelper.getWritableDatabase(); Intent intent = getIntent(); String id = intent.getStringExtra("id"); String[] columns = {"_id", "book_name", "book_isbn", "book_author", "book_press", "book_price"}; String[] selectionArgs = {id}; Cursor cursor = database.query("books", columns, "_id=?", selectionArgs, null, null, null); String[] data = new String[6]; while (cursor.moveToNext()) { data[0] = cursor.getString(0); data[1] = cursor.getString(1); data[2] = cursor.getString(2); data[3] = cursor.getString(3); data[4] = cursor.getString(4); data[5] = cursor.getString(5); } ArrayAdapter<String>adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,data); listView.setAdapter(adapter); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。