当我按下后退按钮时,此ShoppingActivity会被破坏,当我再次访问该活动时,我发现我的回收者视图项目被替换了两次。我该如何解决这个问题?
ShoppingActivity.java 当我再次按下并再次访问该活动时,这里写的所有代码和volley类也被调用,我发现我的回收器视图项被替换了 @覆盖 protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); 的setContentView(R.layout.activity_shopping);
public class Animal {
private Room currentRoom;
private String name;
public Animal() {
}
public Animal(String name) {
setName(name);
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "\t" + name;
}
public void look() {
System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}
public Room getCurrentRoom() {
return this.currentRoom;
}
public void setCurrentRoom(Room currentRoom) {
this.currentRoom = currentRoom;
}
}
这是我的DetailsViewActivity.java
recyclerView = (RecyclerView) findViewById(R.id.rv_recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
btn_sort_name = (Button) findViewById(R.id.btn_name);
btn_sort_price = (Button) findViewById(R.id.btn_price);
tv_total_products = (TextView) findViewById(R.id.totalproduct);
tv_apihits = (TextView) findViewById(R.id.apihits);
tv_total_products.setText(null);
if(savedInstanceState==null){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
BaseUrl,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
int index = 0;
arrayList.clear();
while (index < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(index);
arrayList.add(new Items(jsonObject.getString("name"),
jsonObject.getString("description"),
jsonObject.getString("category"),
jsonObject.getDouble("price"),
jsonObject.getInt("quantity"),
jsonObject.getString("shipping"),
jsonObject.getString("location"),
jsonObject.getString("color"),
jsonObject.getString("link")));
da = jsonObject.getString("name");
Log.d(TAG, da);
index++;
total_products = index;
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerViewAdapter = new RecyclerViewAdapter(arrayList, ShoppingActivity.this);
recyclerView.setAdapter(recyclerViewAdapter);
tv_total_products.append(String.valueOf(total_products));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error");
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
recyclerView.addOnItemTouchListener(new RecyclerViewAdapter.ViewItemClick(getApplicationContext(), recyclerView,
new RecyclerViewAdapter.ItemClickListener() {
@Override
public void clickedItem(View view, int position) {
name = arrayList.get(position).getName();
description = arrayList.get(position).getDescription();
category = arrayList.get(position).getCategory();
shipping = arrayList.get(position).getShipping();
location = arrayList.get(position).getLocation();
color = arrayList.get(position).getColor();
link = arrayList.get(position).getLink();
price = arrayList.get(position).getPrice();
quantity = arrayList.get(position).getQuantity();
DataParcel dataParcel = new DataParcel(name, description, category, shipping, location, color, link, price, quantity);
Intent intent = new Intent(ShoppingActivity.this, DetailsViewActivity.class);
intent.putExtra("data", dataParcel);
startActivity(intent);
}
}));
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
答案 0 :(得分:0)
问题在于您的活动的生命周期,您可以检查从另一个活动返回时第一个活动的实例是否仍然存在。 为了快速修复,您可以在填充数据之前清除您的arraylist,这将清除从其他活动返回时以前添加的数据,您可以将其作为
var mainUIView: UIView!
var scrollView: UIScrollView!
var arrayOfView: [UIView]?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupView() {
// MainUiView
self.mainUIView = UIView(frame: self.frame)
self.addSubview(mainUIView)
// ScrollView
self.scrollView = UIScrollView(frame: self.frame)
self.scrollView.delegate = self
self.addSubview(self.scrollView)
}
func reloadViews(postArray:[Post]?) {
if let postArray = postArray {
print("UIFreeView::reloadVIew.postArraySize = \(postArray.count)")
let size: CGFloat = 80.0
let margin: CGFloat = 20.0
scrollView.contentSize.width = (size * CGFloat(postArray.count))+(margin*CGFloat(postArray.count))
scrollView.contentSize.height = (size * CGFloat(postArray.count))+(margin*CGFloat(postArray.count))
for item in postArray {
let view = buildPostView(item)
self.scrollView.addSubview(view)
}
}
}
fileprivate func buildPostView(_ item:Post) -> UIView {
// Const
let size: CGFloat = 80.0
let margin: CGFloat = 5.0
// Var
let view = UIView()
let textView = UITextView()
let backgroundImageView = UIImageView()
// Setup view
let x = CGFloat(UInt64.random(lower: UInt64(0), upper: UInt64(self.scrollView.contentSize.width)))
let y = CGFloat(UInt64.random(lower: UInt64(0), upper: UInt64(self.scrollView.contentSize.height)))
view.frame = CGRect(x: x,
y: y,
width: size,
height: size)
// Setup background view
backgroundImageView.frame = CGRect(x: 0,
y: 0,
width: view.frame.size.width,
height: view.frame.size.height)
var bgName = ""
if (item.isFromCurrentUser) {
bgName = "post-it-orange"
} else {
bgName = "post-it-white"
}
backgroundImageView.contentMode = .scaleAspectFit
backgroundImageView.image = UIImage(named: bgName)
view.addSubview(backgroundImageView)
// Setup text view
textView.frame = CGRect(x: margin,
y: margin,
width: view.frame.size.width - margin*2,
height: view.frame.size.height - margin*2)
textView.backgroundColor = UIColor.clear
textView.text = item.content
textView.isEditable = false
textView.isSelectable = false
textView.isUserInteractionEnabled = false
view.addSubview(textView)
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
view.addGestureRecognizer(gestureRecognizer)
return view
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.scrollView
}
func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let translation = gestureRecognizer.translation(in: self.scrollView)
// note: 'view' is optional and need to be unwrapped
gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
gestureRecognizer.setTranslation(CGPoint.zero, in: self.scrollView)
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
前
arrayList.clear();
在响应块上。但这只是一个快速修复,而不是实际的解决方案,所以更好的想法是检查类的实例。