Я делаю приложение для электронной коммерции, и на моей стене у меня много продуктов (которые я называю предметами). Таким образом, все эти элементы рассматриваются через пользовательский список listView с именем ListViewAdapter . Каждая строка CustomListView имеет различные представления , такие как TextView , кнопка , image и т. Д. Кнопка , которая у меня есть кнопка «Следующая» (это означает, что если пользователь следит за определенным элементом, за этим следует увидеть, если пользователь не следит за ним, то это должно быть зеленым, говорящим). Впервые мне нужно сделать эту проверку, чтобы увидеть, следует ли следовать за пчел или нет (и эта функция выполняется, выполняя вызов сервера в фоновом режиме и на основе ответа, который я знаю, следовал ли его пчел или нет). Кроме того, мне нужно реализовать функцию, которая, когда я нажимаю на кнопку «Следую за определенным элементом», он выполняет вызов сервера в фоновом режиме (получение результата = 0, если операция преуспела), изменяет цвет и текст. факт, что мне нужно динамически управлять кнопкой
follow < /code> (очевидно, мне нужно использовать Asynctask), но где я могу управлять ею? В классе ItemView или в ListViewAdapter для каждой строки? adapter.notifydatasetchanged () < /code> Но где и как? Я полагаю, что большинство приложений электронной коммерции имеют одинаковое поведение. Не могли бы вы показать мне, как это делается эффективно. Спасибо! < /P>
Вот мой код: < /p>
listviewadapter class < /p>
public class ListViewAdapter extends ArrayAdapter {
private LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList items;
public Bitmap icon;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
@Override
public void remove(String object) {
// TODO Auto-generated method stub
super.remove(object);
}
@Override
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
} else {
view = (ItemView) convertView;
}
Item item = items.get(position);
view.showItems(item);
view.setOnClickListener(new OnItemClickListener(position));
return view;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View v) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
< /code>
itemview class < /p>
public class ItemView extends LinearLayout implements AsyncResponse{
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
public ToggleButton followButton;
public String nextFollowAction = "";
public Integer result1 = 77;
public int statusCode;
public Item item;
public BackgroundTask mBackgroundTask = null;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
//mBackgroundTask.delegate = this;
// TODO Auto-generated constructor stub
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
prezzo = (TextView)findViewById(R.id.tvPrezzo);
scadenza = (TextView)findViewById(R.id.tvScadenza);
followers = (TextView)findViewById(R.id.tvFollowers);
ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
followButton = (ToggleButton)findViewById(R.id.btnFollow);
}
public void showItems(final Item item) {
prezzo.setText(item.getPrezzo());
ic_thumbnail.setImageBitmap(item.getIcon());
scadenza.setText(item.getScadenza());
followers.setText("Followers: " + item.getFollowers());
hProgressBar.setProgress(item.getCoefficient());
askForFollowing("kCheckFollowAction", item, 3);
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Log.i("followButton", "toggle enabled");
followButton.getTextOn();
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long)1);
//askForFollowing(result1, nextFollowAction, item);
//askForFollowing(statusCode, nextFollowAction, item);
increaseFollowers(item);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
} else {
// The toggle is disabled
Log.i("followButton", "toggle disabled");
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long)2);
//askForFollowing(result1, nextFollowAction, item);
followButton.getTextOff();
followButton.setBackgroundResource(R.drawable.action_object_button_green);
decreaseFollowers(item);
}
}
});
}
public void setStatusCode(int statusCode){
this.statusCode = statusCode;
}
public int getStatusCode(Item item, int follow){
//add thread that waits untill you have the statusCode
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long) follow);
return statusCode;
}
public void askForFollowing(String nextFollowAction, Item item, int follow){
Log.i("The statusCode is", Integer.toString(statusCode));
Log.i("The nextFollowAction is", nextFollowAction);
int statusCode = getStatusCode(item, follow);
//Status code: 0 --> OK
if(statusCode == 0) {
Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
nextFollowAction = "kCheckFollowAction";
changeFollowStatus(nextFollowAction, item);
}
// Status code 108 --> Oggetto già seguito
else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 108", "statusCode == 108");
nextFollowAction = "kUnfollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
}
// Status code 122 --> Oggetto non ancora seguito
else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 122", "statusCode == 122");
nextFollowAction = "kFollowAction";
followButton.setEnabled(false);
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
}
}
public void changeFollowStatus(String action, Item item){
Log.i("changeFollowStatus action", action);
if(action.contains("kFollowAction")) {
Log.i("changeFollowStatus", "1");
nextFollowAction = "kUnfollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
followButton.getTextOn();
increaseFollowers(item);
}
else if(action.contains("kUnfollowAction")){
Log.i("changeFollowStatus", "2");
nextFollowAction = "kFollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
followButton.getTextOff();
decreaseFollowers(item);
}
}
public void increaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void decreaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
@Override
public Integer processFinish(Integer result) {
return result;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class BackgroundTask extends AsyncTask {
//public AsyncResponse delegate;
private AsyncResponse listener;
public BackgroundTask(AsyncResponse listener){
this.listener = listener;
}
@Override
protected Integer doInBackground(Long... params) {
// TODO: attempt authentication against a network service.
int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
return i;
}
@Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
}
@Override
protected void onPostExecute(Integer result) {
mBackgroundTask = null;
result1 = listener.processFinish(result);
setStatusCode(result);
//delegate.processFinish(result);
//ItemView
//Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
}
@Override
protected void onCancelled() {
mBackgroundTask = null;
//showProgress(false);
}
}
}
< /code>
comprafragment class < /p>
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
public boolean loading = false;
public boolean get_all_items = false;
//public PullToRefreshScrollView mPullRefreshScrollView;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
private Boolean firstTime = true;
//public ArrayList items = new ArrayList();
public ArrayList items = new ArrayList();
public static ArrayList ids = new ArrayList();
public Bitmap icon;
public int currentItemId = 0;
public Boolean noItems = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
//mDownloadTask.execute((Void) null);
mDownloadTask = new DownloadTask();
mDownloadTask.execute(currentItemId);
return rootView;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class DownloadTask extends AsyncTask {
private ProgressDialog progressDialog;
@Override
protected Boolean doInBackground(Integer... params) {
// TODO: attempt authentication against a network service.
if (firstTime){
ids = MVPFunctions.getInstance().search();
firstTime = false;
}
if (ids.isEmpty()){
noItems = true;
return false;
}
int current_id = params[0];
// 5 elements at a time
int counter = 0;
int size = ids.size();
while (counter previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && visibleItemCount != 0 && ((firstVisibleItem + visibleItemCount) >= (totalItemCount))) {
if ((currentItemId = (totalItemCount))) {
if (currentItemId
Подробнее здесь: https://stackoverflow.com/questions/211 ... istview-wi
Мне нужно динамически управлять поведением кнопки пользовательского списка с Asynctask ⇐ Android
Форум для тех, кто программирует под Android
1748495381
Anonymous
Я делаю приложение для электронной коммерции, и на моей стене у меня много продуктов (которые я называю предметами). Таким образом, все эти элементы рассматриваются через пользовательский список listView с именем ListViewAdapter . Каждая строка CustomListView имеет различные представления , такие как TextView , кнопка , image и т. Д. Кнопка , которая у меня есть кнопка «Следующая» (это означает, что если пользователь следит за определенным элементом, за этим следует увидеть, если пользователь не следит за ним, то это должно быть зеленым, говорящим). Впервые мне нужно сделать эту проверку, чтобы увидеть, следует ли следовать за пчел или нет (и эта функция выполняется, выполняя вызов сервера в фоновом режиме и на основе ответа, который я знаю, следовал ли его пчел или нет). Кроме того, мне нужно реализовать функцию, которая, когда я нажимаю на кнопку «Следую за определенным элементом», он выполняет вызов сервера в фоновом режиме (получение результата = 0, если операция преуспела), изменяет цвет и текст. факт, что мне нужно динамически управлять кнопкой
follow < /code> (очевидно, мне нужно использовать Asynctask), но где я могу управлять ею? В классе ItemView или в ListViewAdapter для каждой строки? adapter.notifydatasetchanged () < /code> Но где и как? Я полагаю, что большинство приложений электронной коммерции имеют одинаковое поведение. Не могли бы вы показать мне, как это делается эффективно. Спасибо! < /P>
Вот мой код: < /p>
listviewadapter class < /p>
public class ListViewAdapter extends ArrayAdapter {
private LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList items;
public Bitmap icon;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
@Override
public void remove(String object) {
// TODO Auto-generated method stub
super.remove(object);
}
@Override
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
} else {
view = (ItemView) convertView;
}
Item item = items.get(position);
view.showItems(item);
view.setOnClickListener(new OnItemClickListener(position));
return view;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View v) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
< /code>
itemview class < /p>
public class ItemView extends LinearLayout implements AsyncResponse{
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
public ToggleButton followButton;
public String nextFollowAction = "";
public Integer result1 = 77;
public int statusCode;
public Item item;
public BackgroundTask mBackgroundTask = null;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
//mBackgroundTask.delegate = this;
// TODO Auto-generated constructor stub
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
prezzo = (TextView)findViewById(R.id.tvPrezzo);
scadenza = (TextView)findViewById(R.id.tvScadenza);
followers = (TextView)findViewById(R.id.tvFollowers);
ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
followButton = (ToggleButton)findViewById(R.id.btnFollow);
}
public void showItems(final Item item) {
prezzo.setText(item.getPrezzo());
ic_thumbnail.setImageBitmap(item.getIcon());
scadenza.setText(item.getScadenza());
followers.setText("Followers: " + item.getFollowers());
hProgressBar.setProgress(item.getCoefficient());
askForFollowing("kCheckFollowAction", item, 3);
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Log.i("followButton", "toggle enabled");
followButton.getTextOn();
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long)1);
//askForFollowing(result1, nextFollowAction, item);
//askForFollowing(statusCode, nextFollowAction, item);
increaseFollowers(item);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
} else {
// The toggle is disabled
Log.i("followButton", "toggle disabled");
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long)2);
//askForFollowing(result1, nextFollowAction, item);
followButton.getTextOff();
followButton.setBackgroundResource(R.drawable.action_object_button_green);
decreaseFollowers(item);
}
}
});
}
public void setStatusCode(int statusCode){
this.statusCode = statusCode;
}
public int getStatusCode(Item item, int follow){
//add thread that waits untill you have the statusCode
mBackgroundTask = new BackgroundTask(ItemView.this);
mBackgroundTask.execute(item.getId(), (long) follow);
return statusCode;
}
public void askForFollowing(String nextFollowAction, Item item, int follow){
Log.i("The statusCode is", Integer.toString(statusCode));
Log.i("The nextFollowAction is", nextFollowAction);
int statusCode = getStatusCode(item, follow);
//Status code: 0 --> OK
if(statusCode == 0) {
Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
nextFollowAction = "kCheckFollowAction";
changeFollowStatus(nextFollowAction, item);
}
// Status code 108 --> Oggetto già seguito
else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 108", "statusCode == 108");
nextFollowAction = "kUnfollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
}
// Status code 122 --> Oggetto non ancora seguito
else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 122", "statusCode == 122");
nextFollowAction = "kFollowAction";
followButton.setEnabled(false);
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
}
}
public void changeFollowStatus(String action, Item item){
Log.i("changeFollowStatus action", action);
if(action.contains("kFollowAction")) {
Log.i("changeFollowStatus", "1");
nextFollowAction = "kUnfollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
followButton.getTextOn();
increaseFollowers(item);
}
else if(action.contains("kUnfollowAction")){
Log.i("changeFollowStatus", "2");
nextFollowAction = "kFollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
followButton.getTextOff();
decreaseFollowers(item);
}
}
public void increaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void decreaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
@Override
public Integer processFinish(Integer result) {
return result;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class BackgroundTask extends AsyncTask {
//public AsyncResponse delegate;
private AsyncResponse listener;
public BackgroundTask(AsyncResponse listener){
this.listener = listener;
}
@Override
protected Integer doInBackground(Long... params) {
// TODO: attempt authentication against a network service.
int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
return i;
}
@Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
}
@Override
protected void onPostExecute(Integer result) {
mBackgroundTask = null;
result1 = listener.processFinish(result);
setStatusCode(result);
//delegate.processFinish(result);
//ItemView
//Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
}
@Override
protected void onCancelled() {
mBackgroundTask = null;
//showProgress(false);
}
}
}
< /code>
comprafragment class < /p>
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
public boolean loading = false;
public boolean get_all_items = false;
//public PullToRefreshScrollView mPullRefreshScrollView;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
private Boolean firstTime = true;
//public ArrayList items = new ArrayList();
public ArrayList items = new ArrayList();
public static ArrayList ids = new ArrayList();
public Bitmap icon;
public int currentItemId = 0;
public Boolean noItems = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
//mDownloadTask.execute((Void) null);
mDownloadTask = new DownloadTask();
mDownloadTask.execute(currentItemId);
return rootView;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class DownloadTask extends AsyncTask {
private ProgressDialog progressDialog;
@Override
protected Boolean doInBackground(Integer... params) {
// TODO: attempt authentication against a network service.
if (firstTime){
ids = MVPFunctions.getInstance().search();
firstTime = false;
}
if (ids.isEmpty()){
noItems = true;
return false;
}
int current_id = params[0];
// 5 elements at a time
int counter = 0;
int size = ids.size();
while (counter previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && visibleItemCount != 0 && ((firstVisibleItem + visibleItemCount) >= (totalItemCount))) {
if ((currentItemId = (totalItemCount))) {
if (currentItemId
Подробнее здесь: [url]https://stackoverflow.com/questions/21158397/i-need-to-dynamically-controll-the-behaviour-of-a-button-of-a-custom-listview-wi[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия