- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在以下情况下保存我的 recyclerview 的状态(当用户按下 fab 按钮时,它会动态地包含 cardviews)
a) 用户关闭应用程序然后重新打开它和b) 当用户从 Activity 转到主屏幕,然后返回 Activity 时
我想要它,以便用户在微调器中输入的卡片 View 和值保存在这些实例上。
我怎样才能做到这一点? Intent ?共享首选项?
create.java 这是带有卡片 View 的 Activity 。我的 mainactivity 代码是主屏幕有 3 个按钮的地方,其中一个按钮转到这个 create.java 屏幕
public class create extends AppCompatActivity {
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
Product mProduct;
private Map<String, String> numberItemValues = new HashMap<>();
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
// RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
findViewById(R.id.relativeLayout).requestFocus();
findViewById(R.id.relativeLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
});
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));
final ProductAdapter adapter = new ProductAdapter(this, productList, numberItemValues);
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
productList.add(mProduct);
if(adapter != null)
adapter.notifyDataSetChanged();
//Handle the empty adapter here
}
});
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
产品适配器
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
private Map<String, String> numberItemValues = new HashMap<>();
// private SearchableSpinner spinner;
//we are storing all the products in a list
private List<Product> productList;
private Activity create;
//TODO CODE FOR CSV FILE
/*InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();*/
InputStream inputStream = null;
List<String> mSpinnerItems = null;
CSVFile csvFile = null;
//TODO END OF CODE FOR CSV FILE
public ProductAdapter(Activity activity) {
create = activity;
}
//getting the context and product list with constructor
/*public ProductAdapter(Activity activity, List<Product> productList) {
// this.mCtx = mCtx;
*//* inputStream = create.getResources().openRawResource(R.raw.shopitems);
csvFile = new CSVFile(inputStream);
mSpinnerItems = csvFile.read();*//*
create = activity;
this.productList = productList;
}*/
public ProductAdapter(Activity activity, List<Product> productList, Map<String, String> numberList) {
numberItemValues = numberList;
create = activity;
this.productList = productList;
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(create);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
// //getting the product of the specified position
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(spinnerArrayAdapter);
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
//TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
/*String currentItem = mSpinnerItems.get(position);
String aisleNumber = numberItemValues.get(currentItem);
holder.textView5.setText(aisleNumber);
*/
//String currentItem = holder.spinner.getSelectedItem().toString();
String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
Set<String> set = numberItemValues.keySet(); for(String key : set) {String value = numberItemValues.get(key); Log.e("DATA ", "key = " + key + " value = " + value); }
//String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
String aisleNumber = numberItemValues.get(currentItem);
holder.textView5.setText(aisleNumber);
Log.e("SELECTION TEST", " Selected map item = " + aisleNumber );
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//binding the data with the viewholder views
if (mSpinnerSelectedItem.containsKey(position)) {
holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
}
holder.getView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
holder.checkBox.setChecked(false);
holder.spinner.setSelection(0);
productList.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
@Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
SearchableSpinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
LinearLayout linearLayout;
View rootView;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
rootView = itemView.findViewById(R.id.linearLayout);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
if(isChecked){
checkBox.setChecked(false);
spinner.setSelection(0);
productList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
}
}
});
}
public View getView() {
return rootView;
}
}
//TODO CODE FOR CSV FILE
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
Product.Java
public class Product {
private static String editText;
private static Boolean checkBox;
private static String textView5;
public static List<String> spinnerItemsList = new ArrayList<String>();
public Product(List spinner, String editText, Boolean checkBox, String textView5) {
this.editText = editText;
this.spinnerItemsList = spinner;
this.checkBox = checkBox;
this.textView5 = textView5;
}
public static String getEdittext () {
return editText;
}
public static boolean getCheckbox () {
return checkBox;
}
public static String getTextview () {
return textView5;
}
public static List<String> getSpinnerItemsList () {
return spinnerItemsList;
}
}
Spinner 的 MyListAdapter 代码
public class MyListAdapter extends ArrayAdapter<String> {
int groupid;
List<String> items;
Context context;
String path;
public MyListAdapter(Context context, int vg, int id, List<String> items) {
super(context, vg, id, items);
this.context = context;
groupid = vg;
this.items = items;
}
static class ViewHolder {
public TextView textid;
public TextView textname;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(groupid, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.textid = (TextView) rowView.findViewById(R.id.txtid);
viewHolder.textname = (TextView) rowView.findViewById(R.id.txtname);
rowView.setTag(viewHolder);
}
// Fill data in the drop down.
ViewHolder holder = (ViewHolder) rowView.getTag();
String row = items.get(position);
//holder.textid.setText(row[0]); //prints aisle number, dont need
holder.textname.setText(row);
return rowView;
}
}
}
最佳答案
您应该将数据保存在sharedPreferences
或database
中,并且每次您打开 Activity 时都从存储的列表中读取数据。
要存储在数据库中,你需要一个像这样的数据库助手类
public class DataBase_CITY extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "";
public static String TABLE;
private static String DB_NAME;
private static String[] FIELD_NAMES;
private static String[] FIELD_TYPES;
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBase_CITY(Context context, String dataBaseName, String tableName,
String[] fieldNames, String[] fieldTypes) {
super(context, dataBaseName, null, 1);
DB_NAME = dataBaseName;
TABLE = tableName;
FIELD_NAMES = fieldNames;
FIELD_TYPES = fieldTypes;
this.myContext = context;
System.err.println(context.getApplicationInfo().dataDir);
DB_PATH = context.getApplicationInfo().dataDir + File.separator
+ "databases" + File.separator;
System.out.println(DB_PATH);
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
// Toast.makeText(myContext, "already exist",
// Toast.LENGTH_LONG).show();
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
// throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
// Toast.makeText(myContext, "already exist",
// Toast.LENGTH_LONG).show();
} catch (SQLiteException e) {
// database does't exist yet.
// Toast.makeText(myContext, "not already exist",
// Toast.LENGTH_LONG).show();
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
*/
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the Input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE + " (UserID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ FIELD_NAMES[0] + " " + FIELD_TYPES[0] + ", "
+ FIELD_NAMES[1] + " " + FIELD_TYPES[1] + ", "
+ FIELD_NAMES[2] + " " + FIELD_TYPES[2] + ")");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
public void updateDB(String[] arguments) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_NAMES[0], Integer.parseInt(arguments[0]));
values.put(FIELD_NAMES[1], arguments[1]);
values.put(FIELD_NAMES[2], Integer.parseInt(arguments[2]));
db.insert(TABLE, null, values);
db.close();
}
}
要在其中存储数据,您需要以下方法
private static void updateCityTable(String TableName, int id, String name, int
province_id) {
DataBase_CITY helper = new DataBase_CITY(G.CONTEXT,
"CITY_DATABASE", TableName, G.CityTableFields, G.CityTableFieldTypes);
try {
helper.updateDB(new String[]{
String.valueOf(id),
name,
String.valueOf(province_id)});
} catch (Exception e) {
e.printStackTrace();
}
}
你可以像这样从数据库中读取
private String cityDataBaseChecker(String TableName, String column, String columnName, String amount) {
DataBase_PROVINCE helper = new DataBase_PROVINCE(G.CONTEXT,
"CITY_DATABASE", TableName, G.CityTableFields, G.CityTableFieldTypes);
try {
helper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
SQLiteDatabase sqld = helper.getWritableDatabase();
Cursor cursor = sqld.rawQuery("select * from " + TableName + " where " + columnName + "=\"" + amount + "\" order by " + column, null);
String title = null;
if (cursor.moveToFirst()) {
do {
title = cursor.getString(cursor.getColumnIndex(column));
System.out.println("city =" + title);
} while (cursor.moveToNext());
}
sqld.close();
return title;
}
您可以像这样定义字段名称和类型
public static String[] CityTableFields = new String[]{"id", "name", "province_id"};
public static String[] CityTableFieldTypes = new String[]{"INT", "TEXT", "INT"};
关于android - 保存我的 recyclerview 和 cardview 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576623/
我在另一个 RecyclerView(parentRecyclerView) 中实现了 RecyclerView(childRecyclerView),图片说明了所有的实现: 我想编写一个 espre
我正在构建一个应用程序,它使用ViewPager2在页面之间水平滚动,每个页面都有一个垂直滚动的内容RecyclerView,其中每个列表的第一个位置都有一行水平滚动小部件,例如附加到寻呼机指示器类型
我正在尝试实现一个水平的 recyclerview 并且 recyclerview 的每个项目都将是一个具有网格布局的垂直 recyclerview。我面临的问题是,当我尝试垂直滚动子 recycle
我使用显示条目列表的 RecyclerView。每个条目都托管另一个 RecyclerView,它是一个图像列表。 我现在想让这个嵌套的 RecyclerView 可点击,而不是它的项目,而是整个 V
我正在尝试将手机中的图像加载到我的回收 View 中。 到目前为止,我已经创建了一个 recyclerview.adapter 和一个 gridlayoutmanager,并将它们附加到我的 recy
我需要一个可扩展 View ,其中父/可扩展标题将具有文本和下拉箭头。每个此类标题的子项应该是在网格结构中具有多个项目的 View 。 (有点像带有 GridLayoutManager 的回收器 Vi
我正在使用显示不同类别列表的 RecyclerView。每行项目还包含 RecyclerView 以显示类别项目列表。父级 RecyclerView 由垂直 LinearLayoutManager 填
我正在更新一个旧的 Android 项目,现在我从 RecyclerView 中反复收到这条日志语句: W/RecyclerView:RecyclerView 不支持滚动到绝对位置。改为使用 scro
在我的 Adapter 中,我调用 LayoutManager.ChildAt(position) 来获取 itemview,但是我得到的 View 不是匹配的 itemview,当我调用 notif
我正在从 ListView 迁移到 RecyclerView,但是在 SQLite 中输入一些数据后,我的列表没有使用 notifyDataSetChanged() 更新;所以我总是要调用setAda
我正在用 Google Now Cards 的风格创建一组 5 张卡片。我首先关注的是总体布局。 我正在使用 CardView 和 RecyclerView ,我想要实现的是这样的: 这是我的 Car
在我的应用程序中,我有一个 RecyclerView,其中包含一个简单的项目 View ,每行包含一个 TextView 和一个 Spinner。 用户从操作栏中单击“保存”后,我需要遍历所有项目并获
我正在尝试检查 RecyclerView 中是否可以看到某些特定项目;但我无法实现。请帮助我确定我的项目是否在 RecyclerView 中完全可见。 mrecylerView.addOnScroll
我有一个提要片段,它的主要元素是帖子的 RecyclerView。 我正在使用 Lisa Wray 的 Groupie 库管理回收站 https://github.com/lisawray/group
我有这两个类似的行为回收器 View 适配器,它们之间的唯一区别是 onclick 方法和传递给它们的对象。所以,我正在考虑将类 B 设计为从回收器 View 适配器继承,这样我就可以更改构造函数来执
这很奇怪。我对这个问题感到沮丧。我将数据保存在 ArrayList 中。当我将数据放在 RecyclerView 上时。数据未显示在列表中。这是我的代码 listOrder.forEach { ord
编辑我通过使用 CoordinatorLayout 和 AppBarLayout 作为 header 和 TabLayout 的包装解决了这个问题。本来应该很明显,但是哦,好吧。 原始问题:我有一个设
我有一个回收 View 。我想从其适配器类更新回收器 View 。我尝试了 notiftDataSetChanged( ) 但它只适用于主类。下面是 recyclerview 适配器类的代码。 pac
我正在使用具有不同 viewholders 的 recyclerview(具有垂直 LinearLayout),其中一个有另一个 RecyclerView(带有水平 LL)。在第二个 recycler
我想创建一个与 Google Play Store 或 Netflix App 类似的布局,其中在单个 RecyclerView 中基本上有多个水平 RecyclerView。如果这不是他们做事的方式
我是一名优秀的程序员,十分优秀!