Java Android自定义listview在第一个位置显示最后一项
当我在listview中插入新产品时,该产品将显示在listview中的最后一个位置。现在我想在listview的第一个位置显示最近添加的产品。例如,我的数组产品最初在listview中显示为这样,0>1>2>3,现在我想显示为这样,3>2>1>0。我应该如何在代码中实现它?谢谢你的帮助 AllProductActivity.javaJava Android自定义listview在第一个位置显示最后一项,java,android,listview,android-listview,Java,Android,Listview,Android Listview,当我在listview中插入新产品时,该产品将显示在listview中的最后一个位置。现在我想在listview的第一个位置显示最近添加的产品。例如,我的数组产品最初在listview中显示为这样,0>1>2>3,现在我想显示为这样,3>2>1>0。我应该如何在代码中实现它?谢谢你的帮助 AllProductActivity.java public class AllProductActivity extends ListActivity { // Progress Dialog //priv
public class AllProductActivity extends ListActivity {
// Progress Dialog
//private ProgressDialog pDialog;
private SweetAlertDialog pDialog;
// Creating JSON Parser object
JSONParser2 jParser = new JSONParser2();
// array list that hold original data
ArrayList<HashMap<String, String>> productsList;
//Array list taht hold search result
ArrayList<HashMap<String, String>> searchResults;
ListView list;
LazyAdapter adapter;
// url to get all products list
private static String url_all_products = "http://gemini888.tk/test4/android_connect/get_all_products.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_PRODUCTS = "products";
public static final String TAG_PID = "uid";
public static final String TAG_NAME = "itemname";
public static final String TAG_PRICE = "price";
public static final String TAG_PATH = "path";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
list = (ListView)findViewById(android.R.id.list);
final TextView noProduct = (TextView) findViewById(android.R.id.empty);
//testing
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
searchBox.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// get text in edittext
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear initial data
searchResults.clear();
for(int i=0; i<productsList.size();i++){
String listItemName = productsList.get(i).get(TAG_NAME).toString();
if(textLength<= listItemName.length()){
if(searchString.equalsIgnoreCase(listItemName.substring(0,textLength))){
searchResults.add(productsList.get(i));
}
}else {
noProduct.setText("no items found in our market! Please search again. Make sure all words are spelled correctly.");
}
}
adapter.notifyDataSetChanged();
}
});
// on seleting single product
// launching Edit Product Screen
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewDetailsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(AllProductActivity.this);
//pDialog.setMessage("Loading products. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
pDialog = new SweetAlertDialog(AllProductActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading products. Please wait...");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String iname = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String path = c.getString(TAG_PATH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, iname);
map.put(TAG_PRICE, price);
map.put(TAG_PATH, path);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
searchResults = new ArrayList<HashMap<String,String>>(productsList);
adapter=new LazyAdapter(AllProductActivity.this, searchResults);
list.setAdapter(adapter);
}
});
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
private class ViewHolder{
ImageView thumb_image;
TextView pid, itemname, price;
}
ViewHolder viewHolder;
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.pid = (TextView)vi.findViewById(R.id.pid);
viewHolder.itemname = (TextView)vi.findViewById(R.id.name);
viewHolder.price = (TextView)vi.findViewById(R.id.price);
viewHolder.thumb_image = (ImageView)vi.findViewById(R.id.imageView1); //
vi.setTag(viewHolder);
}else
viewHolder=(ViewHolder) vi.getTag();
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
viewHolder.pid.setText(song.get(AllProductActivity.TAG_PID));
viewHolder.itemname.setText(song.get(AllProductActivity.TAG_NAME));
viewHolder.price.setText(song.get(AllProductActivity.TAG_PRICE));
imageLoader.DisplayImage(song.get(AllProductActivity.TAG_PATH), viewHolder.thumb_image); //
Animation animation;
animation = AnimationUtils.loadAnimation(activity, R.anim.left_to_right);
//animation = AnimationUtils.loadAnimation(activity, (position > lastPosition) ?
// R.anim.up_from_bottom : R.anim.down_from_top);
vi.startAnimation(animation);
return vi;
}
}
公共类AllProductActivity扩展了ListActivity{
//进度对话框
//私人对话;
私人对话;
//创建JSON解析器对象
JSONParser2 jParser=新的JSONParser2();
//保存原始数据的数组列表
ArrayList productsList;
//保存搜索结果的数组列表
ArrayList搜索结果;
列表视图列表;
懒散适配器;
//获取所有产品列表的url
私有静态字符串url\u所有产品=”http://gemini888.tk/test4/android_connect/get_all_products.php";
//JSON节点名称
公共静态最终字符串标记_SUCCESS=“SUCCESS”;
公共静态最终字符串TAG_PRODUCTS=“PRODUCTS”;
公共静态最终字符串标记_PID=“uid”;
公共静态最终字符串标记_NAME=“itemname”;
公共静态最终字符串TAG_PRICE=“PRICE”;
公共静态最终字符串标记_PATH=“PATH”;
//产品JSONArray
JSONArray产品=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.all_产品);
最终EditText搜索框=(EditText)findViewById(R.id.searchBox);
list=(ListView)findViewById(android.R.id.list);
final TextView noProduct=(TextView)findViewById(android.R.id.empty);
//测试
如果(android.os.Build.VERSION.SDK_INT>9)
{
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
}
//ListView的Hashmap
productsList=新的ArrayList();
//在后台线程中加载产品
新建LoadAllProducts().execute();
addTextChangedListener(新的TextWatcher(){
@凌驾
公共无效后文本已更改(可编辑){
//TODO自动生成的方法存根
}
@凌驾
更改前的公共无效(字符序列、整数开始、,
整数计数,整数后){
//TODO自动生成的方法存根
}
@凌驾
public void onTextChanged(字符序列,int start,int before,
整数计数){
//获取edittext中的文本
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
//清除初始数据
searchResults.clear();
对于(int i=0;i要执行此操作,只需更改getItem()
逻辑即可
@Override
public Object getItem(int position) {
return getCount() - position - 1;
}
比如说,如果总计数是2,那么,{索引:0,1}
对于第一项(索引=0):
2-0-1=1(最后一个索引)
对于第二项(索引=1):
2-1-1=0(第一个索引)我认为最好让服务器进行排序,在SQL选择中使用“orderby”
如果你在安卓应用程序中进行排序,一旦数据库发生变化,或者业务逻辑得到改善,你必须在应用程序中重写排序代码,并让所有用户在应用程序中更新。你可以随时在服务器上更改排序算法。我解决了(黑客攻击了?)将新项添加到ArrayList的0索引中也会出现类似的问题,该索引通过ArrayAdapter更新ListView
不过,我以后不会阅读列表,因此列表结构可能会有问题,但我所关心的只是在ListView顶部添加最新条目的视觉效果
ListView mListView = (ListView) findViewById(R.id.mListView);
//new ArrayAdapter using the activity, a design element for the list, and the list with data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//assign the adapter to the listView
mListView.setAdapter(adapter);
不能反转基础集合吗?元素的显示顺序与它存储在hashmap中的顺序完全相同。简单方法-将hashmap更改为任何更好的类型…ArrayList或somth。
//add the entry to the 0th index of the list. This will make the entry appear at the top
list.add(0,""+ resetsToList +": "+currentCount+"");
//tell the adapter that the dataset has changed. This will update the listView
adapter.notifyDataSetChanged();