I'd like to implement a ListView animation with an ImageView on the left and text on the right and I'm using an Adapter that gives a ListView the animations, and they're awesome, so I'd like to know how I can modify the class, particularly, the adapter to show a ListView with an ImageView on the left. Here's the class:
public class Post extends SherlockActivity implements
PullToRefreshAttacher.OnRefreshListener, OnItemLongClickListener,
OnItemClickListener {
private PullToRefreshAttacher mPullToRefreshAttacher;
private ListView listview;
private DisplayMetrics metrics;
ActionMode mMode;
Animation animation;
Intent i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
sessionCheck();
}
private void sessionCheck() {
// TODO Auto-generated method stub
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
listview = new ListView(this);
listview.setFadingEdgeLength(0);
ArrayList<String> strings = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
strings.add("That's list number " + (i + 1));
}
MainAdapter mAdapter = new MainAdapter(this, strings, metrics);
listview.setAdapter(mAdapter);
listview.setOnItemLongClickListener(this);
listview.setOnItemClickListener(this);
setContentView(listview);
pullToRefresh();
} else {
Toast.makeText(getApplicationContext(), "Please log in first",
Toast.LENGTH_LONG).show();
i = new Intent(getApplicationContext(), StartBase.class);
startActivity(i);
}
}
private void pullToRefresh() {
// TODO Auto-generated method stub
PullToRefreshAttacher.Options ptrOptions = new PullToRefreshAttacher.Options();
ptrOptions.refreshScrollDistance = 0.6f;
ptrOptions.headerLayout = R.layout.customised_header;
ptrOptions.headerTransformer = new CustomisedHeaderTransformer();
mPullToRefreshAttacher = PullToRefreshAttacher.get(this, ptrOptions);
PullToRefreshAttacher.ViewDelegate handler = new AbsListViewDelegate();
mPullToRefreshAttacher.addRefreshableView(listview, handler, this);
}
#Override
public void onRefreshStarted(View view) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
static class CustomisedHeaderTransformer extends
PullToRefreshAttacher.HeaderTransformer {
private View mHeaderView;
private TextView mMainTextView;
private TextView mProgressTextView;
#Override
public void onViewCreated(Activity activity, View headerView) {
mHeaderView = headerView;
mMainTextView = (TextView) headerView.findViewById(R.id.ptr_text);
mProgressTextView = (TextView) headerView
.findViewById(R.id.ptr_text_secondary);
}
#Override
public void onReset() {
mMainTextView.setVisibility(View.VISIBLE);
mMainTextView.setText(R.string.pull_to_refresh_pull_label);
mProgressTextView.setVisibility(View.GONE);
mProgressTextView.setText("");
}
#Override
public void onPulled(float percentagePulled) {
mProgressTextView.setVisibility(View.VISIBLE);
mProgressTextView
.setText(Math.round(100f * percentagePulled) + "%");
}
#Override
public void onRefreshStarted() {
mMainTextView.setText(R.string.pull_to_refresh_refreshing_label);
mProgressTextView.setVisibility(View.GONE);
}
#Override
public void onReleaseToRefresh() {
mMainTextView.setText(R.string.pull_to_refresh_release_label);
}
#Override
public void onRefreshMinimized() {
// In this header transformer, we will ignore this call
}
#Override
public boolean showHeaderView() {
final boolean changeVis = mHeaderView.getVisibility() != View.VISIBLE;
if (changeVis) {
mHeaderView.setVisibility(View.VISIBLE);
}
return changeVis;
}
#Override
public boolean hideHeaderView() {
final boolean changeVis = mHeaderView.getVisibility() != View.GONE;
if (changeVis) {
mHeaderView.setVisibility(View.GONE);
}
return changeVis;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
SubMenu subMenu1 = menu.addSubMenu("Categories");
subMenu1.add(0, 1, Menu.NONE, "One");
subMenu1.add(0, 2, Menu.NONE, "Two");
subMenu1.add(0, 3, Menu.NONE, "Three");
subMenu1.add(0, 4, Menu.NONE, "Four");
subMenu1.add(0, 5, Menu.NONE, "Five");
subMenu1.add(0, 6, Menu.NONE, "Six");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setIcon(android.R.drawable.ic_dialog_info);
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case R.id.action_account:
i = new Intent(getApplicationContext(), Account.class);
startActivity(i);
break;
case R.id.action_logout:
Toast.makeText(getApplicationContext(), "Working on this...",
Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
public class MainAdapter extends ArrayAdapter<String> {
private Context context;
private LayoutInflater mInflater;
private ArrayList<String> strings;
private DisplayMetrics metrics_;
private class Holder {
public TextView textview;
}
public MainAdapter(Context context, ArrayList<String> strings,
DisplayMetrics metrics) {
super(context, 0, strings);
this.context = context;
this.mInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.strings = strings;
this.metrics_ = metrics;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final String str = this.strings.get(position);
final Holder holder;
if (convertView == null) {
convertView = mInflater.inflate(
android.R.layout.simple_list_item_1, null);
convertView.setBackgroundColor(0xFF202020);
holder = new Holder();
holder.textview = (TextView) convertView
.findViewById(android.R.id.text1);
holder.textview.setTextColor(0xFFFFFFFF);
holder.textview.setBackgroundResource(R.drawable.list_selector);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.textview.setText(str);
animation = animation = AnimationUtils.loadAnimation(context,
R.anim.push_left_in);
animation.setDuration(200);
convertView.startAnimation(animation);
animation = null;
return convertView;
}
}
private final class AnActionModeOfEpicProportions implements
ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add("One").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Two").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Three").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Four").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Five").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Six").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Toast.makeText(getApplicationContext(), "Got click: " + item,
Toast.LENGTH_SHORT).show();
mode.finish();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mMode = startActionMode(new AnActionModeOfEpicProportions());
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "List item selected",
Toast.LENGTH_LONG).show();
}
}
I've just copy pasted everything :-) The adapter you're looking for is MainAdapter...way down there. Please help me out.
You should modify this part:
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
convertView.setBackgroundColor(0xFF202020);
holder = new Holder();
holder.textview = (TextView) convertView.findViewById(android.R.id.text1);
holder.textview.setTextColor(0xFFFFFFFF);
holder.textview.setBackgroundResource(R.drawable.list_selector);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
So, android.R.layout.simple_list_item_1 is the layout that is used for list items. It contains only one TextView. To add ImageView you should use custom list item layout, for example this one:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight">
<ImageView
android:id="#+id/pic"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/your_custom_image"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="8dp"/>
</LinearLayout>
Put it in XML file into res\layout directory and name it custom_list_item.xml. Then just replace android.R.layout.simple_list_item_1 with R.layout.custom_list_item and android.R.id.text1 with R.id.text in your code.
Thats all! Animation stays the same.
If you want to change image for each list item then you also should:
add ImageView imageView field into Holder class
add
holder.imageView = (ImageView) convertView.findViewById(R.id.pic);
after
holder.textview.setBackgroundResource(R.drawable.list_selector);
add
holder.imageView.setImage(R.drawable.my_drawable);
after
holder.textview.setText(str);
Change R.drawable.my_drawable to your custom drawable if needed.
Related
I have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.
I would like to pass the selected item "id" from listview to popupMenu , the mainActivity:
public class ListChildrenActivity extends AppCompatActivity implements Config, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "ListChildrenActivity";
ProgressDialog progressDialog;
Toolbar toolbar;
ChildrenAdapter adapter;
ListView listView;
int idConnexion, id;
private SwipeRefreshLayout refreshLayout;
Intent intent;
Child childObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_child);
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Listes des enfants");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), MainMedecinActivity.class);
startActivity(intent);
}
});
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
showChildren();
}
});
showChildren();
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View view, int itemInt, long lng) {
//String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
//Toast.makeText(ListChildrenActivity.this, selectedFromList, Toast.LENGTH_SHORT).show();
//TextView v = (TextView)view.findViewById(R.id.tv);
//String itemId = v.getText().toString();
childObj = (Child) listView.getItemAtPosition(itemInt);
id = childObj.getIdEnfant();
Toast.makeText(ListChildrenActivity.this, ""+id, Toast.LENGTH_SHORT).show();
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
}
private ArrayList<Child> generateData(String content) {
ArrayList<Child> children = new ArrayList<Child>();
JSONObject jObj = null;
JSONArray ja = null;
try {
ja = new JSONArray(content);
for (int i = 0; i < ja.length(); i++) {
jObj = ja.getJSONObject(i);
children.add(new Child(jObj.getInt("idEnfant"), jObj.getString("nomEnfant"), jObj.getString("prenomEnfant")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return children;
}
public void showChildren() {
if (!validate()) {
failed();
return;
}
SharedPreferences prefs = getSharedPreferences("Info_Connexion", Context.MODE_PRIVATE);
idConnexion = prefs.getInt("idConnexion", 0);
progressDialog = new ProgressDialog(ListChildrenActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("La liste des enfants ...");
progressDialog.show();
if (isOnline()) {
requestData(SERVER_URL + "enfant/read/", idConnexion);
} else {
Toast.makeText(ListChildrenActivity.this, "Eroor network", Toast.LENGTH_SHORT).show();
}
}
private void requestData(String url, int id) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
RequestPackage p = new RequestPackage();
p.setMethod("POST");
p.setUri(url);
p.setParam("idMedecin", String.valueOf(id));
MessagesTask task = new MessagesTask();
task.execute(p);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public void success(final int id, final ProgressDialog progressDialog, String content, SwipeRefreshLayout refreshLayout) {
// 1. pass context and data to the custom adapter
adapter = new ChildrenAdapter(this, generateData(content));
// 2. Get ListView from activity_main.xml
// 3. setListAdapter
listView.setAdapter(adapter);
if (id != 0) {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
} else {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
Toast.makeText(ListChildrenActivity.this, "Eroor server or input", Toast.LENGTH_SHORT).show();
}
}
public boolean validate() {
boolean valid = true;
return valid;
}
public void failed() {
Toast.makeText(getBaseContext(), "List Children failed", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
TextView scoreView = (TextView) findViewById(R.id.score);
switch (item.getItemId()) {
case R.id.infos:
intent = new Intent(getBaseContext(), ChildInformationsActivity.class);
intent.putExtra("idEnfant", id );
startActivity(intent);
return true;
case R.id.signes_diagnostic:
intent = new Intent(getBaseContext(), ChildSignesDiagnosticActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.bilan_bio:
intent = new Intent(getBaseContext(), ChildBilanBioActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.traitement_medical:
intent = new Intent(getBaseContext(), ChildTraitementMedicalActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.imagerie:
intent = new Intent(getBaseContext(), ChildImagerieActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
default:
return false;
}
}
private class MessagesTask extends AsyncTask<RequestPackage, String, String> {
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
#Override
protected void onPostExecute(String content) {
Log.i(TAG, "------------------------" + content);
success(idConnexion, progressDialog, content, refreshLayout);
}
}
}
enter image description here
class adapter:
public class ChildrenAdapter extends ArrayAdapter<Child> {
private final Context context;
private final ArrayList<Child> childrenArrayList;
public ChildrenAdapter(Context context, ArrayList<Child> childrenArrayList) {
super(context, R.layout.row_child, childrenArrayList);
this.context = context;
this.childrenArrayList = childrenArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowChildView = inflater.inflate(R.layout.row_child, parent, false);
// 3. Get the two text view from the rowView
TextView nameView = (TextView) rowChildView.findViewById(R.id.name);
TextView dateView = (TextView) rowChildView.findViewById(R.id.date);
TextView scoreView = (TextView) rowChildView.findViewById(R.id.score);
// 4. Set the text for textView
//String text = childrenArrayList.get(position).getNomEnfant())+" "+childrenArrayList.get(position).getNomEnfant();
nameView.setText(childrenArrayList.get(position).getNomEnfant()+" "+childrenArrayList.get(position).getPrenomEnfant());
dateView.setText("22/12/2012");
scoreView.setText(String.valueOf(childrenArrayList.get(position).getIdEnfant()));
scoreView.setBackgroundResource(R.drawable.circular_textview);
// 5. retrn rowView
return rowChildView;
}
}
Whene i click to the row of listview i get the "id" but how i can pass it to the popupMenu.
The solution: it just add settag(position) to imageview in getview, then :
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
listView.performItemClick(v, (Integer) v.getTag(),listView.getItemIdAtPosition((Integer) v.getTag()));
}
You can use interface to communicate between them
In your adapter class, initialize
private OnItemSelectedListener mListener;
and add these methods
public void setOnItemClickLister(OnItemSelectedListener mListener) {
this.mListener = mListener;
}
//Creating an interface
public interface OnItemSelectedListener {
public void onItemSelected(String s);
}
in onClick function in adapter
use this
mListener.onItemSelected(id);
//id is your string
you can call it in MainActivity,
adapter.setOnItemClickLister(new OnItemSelectedListener() {
#Override
public void onItemSelected(String s) {
//you will get the string here, you can pass it as an argument in popup menu
}
});
On the adapter Side:
view.findViewById(R.id.menu_btn).setTag(id);
On the ListActivity Side:
public void showPopUp(View v){
currentId = v.getTag().toString();
PopupMenu popupMenu=new PopupMenu(this,v);
popupMenu.setOnMenuItemClickListener(ListActivity.this);
MenuInflater inflater=popupMenu.getMenuInflater();
inflater.inflate(R.menu.my_pop_up,popupMenu.getMenu());
popupMenu.show();
}
On XML side:
<ImageButton android:id="#+id/menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_overflow"
android:layout_marginStart="10dp"
android:layout_marginEnd="20dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:onClick="showPopUp"/>
Note: onClick="showPopUp" is very critical here.
This should be helpful. Thank you.
i have two activites,transporting arraylist imageurls to activity AddProductActivity from activity Sdcard. The Sdcard.java code is:
public class Sdcard extends Activity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
ImageLoader imageLoader;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photoalbum);
getActionBar();
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setTitle("select image");
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => " + imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.album_gridview);
gridView.setAdapter(imageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(Sdcard.this, AddProductActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.select_image_submit:
ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
if (selectedItems.size() == 0) {
Toast.makeText(getBaseContext(), "no selected imageļ¼", Toast.LENGTH_LONG)
.show();
} else if (selectedItems.size() > 9) {
Toast.makeText(getBaseContext(), "must below 9 images", Toast.LENGTH_LONG)
.show();
} else {
Intent intent1 = new Intent(this, AddProductActivity.class);
intent1.putStringArrayListExtra("select_image", selectedItems);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
setResult(9392,intent1);
finish();
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ProgressBar spinner = (ProgressBar) findViewById(R.id.loading_image_fromsdcard);
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.photoalbum_gridview_item, null);
}
CheckBox mCheckBox = (CheckBox) convertView
.findViewById(R.id.select_image_cb);
final ImageView imageView = (ImageView) convertView
.findViewById(R.id.photo_img_view);
imageLoader.displayImage("file://" + imageUrls.get(position),
imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(Sdcard.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim =AnimationUtils.loadAnimation(Sdcard.this,
R.anim.push_left_in);
imageView.setAnimation(anim);
anim.start();
}
});
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"selected item is " + position, Toast.LENGTH_LONG)
.show();
}
});
mCheckBox.setTag(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mSparseBooleanArray.put((Integer) buttonView.getTag(),
isChecked);
}
};
}
}
and activity AddProductActivity recive imageurls from activity Sdcard and display image on it, like the code
public class AddProductActivity extends Activity{
GridView gridView;
private String image;
private static final int GALLERY_REQUEST = 9390;
private DisplayImageOptions options;
ImageLoader imageLoader;
private ArrayList<String> selectImageUrls;
String[] f;
private SelectImageAdapter selectImageAdapter;
ImageView imageView;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("add product");
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory().cacheOnDisc().build();
gridView = (GridView) findViewById(R.id.select_image_gridview);
this.selectImageUrls = new ArrayList<String>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_product, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(AddProductActivity.this,
MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.action_upload_picture:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onSelectFromSD(MenuItem item) {
Intent selectFromSdcard = new Intent(AddProductActivity.this,Sdcard.class);
startActivityForResult(selectFromSdcard, GALLERY_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("[requestCode=" + requestCode + "]" + "[resultCode="
+ resultCode + "]");
if (requestCode == GALLERY_REQUEST && resultCode == 9392
&& data != null) {
// image = data.getData().toString();
selectImageUrls = data.getStringArrayListExtra("select_image");
if (selectImageUrls != null) {
// System.out.println("recieve =" + selectImageUrls.size());
f = (String[]) selectImageUrls
.toArray(new String[selectImageUrls.size()]);
if (selectImageAdapter == null) {
selectImageAdapter = new SelectImageAdapter(this,
selectImageUrls);
imageLoader.init(ImageLoaderConfiguration
.createDefault(this));
gridView.setAdapter(selectImageAdapter);
selectImageAdapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
startFullImagePagerActivity(position);
}
});
} else {
selectImageAdapter.notifyDataSetChanged();
}
} else {
return;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
protected void startFullImagePagerActivity(int position) {
// TODO Auto-generated method stub
Intent i = new Intent(AddProductActivity.this,
FullScreenViewActivity.class);
i.putStringArrayListExtra("position_url", selectImageUrls);
i.putExtra("position", position);
startActivity(i);
}
public class SelectImageAdapter extends BaseAdapter {
LayoutInflater mInflater;
Context mContext;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.select_image, null);
}
final ImageView imageView = (ImageView) convertView.findViewById(R.id.select_images);
final ProgressBar spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position), imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
spinner.setVisibility(View.GONE);
notifyDataSetChanged();//followed with Armin's suggestion
}
});
return convertView;
}
}
but when it returned activity AddProductActivity,the images did not appear in gridview ,if i clicked the editorText to active the keyboard,the images appearing in the gridview. So i am puzzled,waiting for some suggestions, thanks!
image url :http://i61.tinypic.com/2ch9onq.png
actived keyboard image appearing: http://i61.tinypic.com/2l8uumc.png
if i used this getView() method in AddProductActivity,it works fine.
#Override
public View getView(final int position, View convertView, ViewGroup
parent)
{
if (convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(245, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else {
imageView = (ImageView) convertView;
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false ;
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true ;
Bitmap bitmap = BitmapFactory.decodeFile(selectImageUrls.get(position), bmOptions);
imageView.setImageBitmap(bitmap);
return imageView;
}
but it does not smooth when it transfored the imageurls back to AddProductActivity.
Try to replace adapter code.
public class SelectImageAdapter extends BaseAdapter {
Context mContext;
ViewHolder holder;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.select_image, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.select_images);
holder.spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position),holder.imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
holder.spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
holder.spinner.setVisibility(View.GONE);
}
});
return convertView;
}
class ViewHolder {
ImageView imageView;
ProgressBar spinner;
}
}
I believe what is missing in the code is a call to notifyDataSetChanged() after the images are loaded (in onLoadingComplete() callback of the listener).
The way the above code is written, if notifyDataSetChanged() is called in onLoadingComplete(), it will solve the problem that you have.
However, calling notifyDataSetChanged() every time in that callback method, may degrade the performance significantly. The more images you have, the more the performance may drop.
If you do observe performance drop by doing the above, to solve it, I would suggest using an image refresh helper mechanism. This way you can either call notifyDataSetChanged():
after n images have been loaded
or after every t seconds has passed
I hope the information above helps you.
Here is the thing..
I have one activity in which i have implmented the ActionBarSherlock,View Pager with Tab Navigation.
In Action Bar i have placed the search view.Now i am adding the list of fragments from the activity using viewPagerAdapter.
Now, In fragments i have placed the expandable listview and i am display the products with its section name in the expandable listview.
What i want to do ::
I want to perform the search of products from the expandable listview.
Problem which i have faced ::
I have placed the searchview in the Activity from which i am calling the different fragments.So how to perform the search ???
My code ::
Activity ::
public class Activity extends SherlockFragmentActivity implements TabListener,SearchView.OnQueryTextListener,SearchView.OnSuggestionListener
{
TabHost tabHost;
TabHost.TabSpec spec;
Intent intent;
Resources res;
Context mContext;
ProgressDialog pd=null;
Handler handler=new Handler();
MD5Generator md5Generator=new MD5Generator();
HttpConn httpConn=new HttpConn();
MyAccountInfo myAccountInfo;
private UserInfo userInfo=new UserInfo();
private Calendar cal = Calendar.getInstance();
private AppPreferences preference;
ArrayList<String> menuInfo;
//private ActionBar actionBar;
private ActionBarTabMenuAdapter actionbartabmenuAdapter;
private ViewPager awesomePager;
DataHelper dataHelper;
ArrayList<Integer> servicesImage;
ArrayList<String> servicesName;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ActionBar actionBar=getSupportActionBar();
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mContext=this;
// getSupportActionBar().setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));
// getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// getSupportActionBar().setDisplayUseLogoEnabled(false);
// getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header_color)));
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
dataHelper=new DataHelper(this);
menuInfo=dataHelper.getTransMenuInfo();
servicesName = new ArrayList<String>();
servicesImage = new ArrayList<Integer>();
if(menuInfo.contains("1"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("1"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("2"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("2"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("4"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("4"));
servicesImage.add(R.drawable.abs__ic_search);
}
dataHelper.close();
servicesName.add("My Account");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("myacc");
servicesName.add("Reports");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Reports");
servicesName.add("Settings");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Settings");
List<Fragment> fragments = getFragments();
actionbartabmenuAdapter = new ActionBarTabMenuAdapter(getSupportFragmentManager(), fragments,this,servicesName,servicesImage);
awesomePager.setAdapter(actionbartabmenuAdapter);
System.out.println(" **** Selected Item==>"+awesomePager.getCurrentItem());
awesomePager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
for (int i = 0; i < actionbartabmenuAdapter.getCount(); i++) {
Tab tab = actionBar.newTab();
//tab.setText(awesomeAdapter.getPageTitle(i));
tab.setText(servicesName.get(i));
tab.setIcon(servicesImage.get(i));
tab.setTabListener(this);
actionBar.addTab(tab);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Code Comes here...
System.out.println("Key Event:"+event.getAction()+",keyCode"+keyCode);
onBackPressed();
return true;
}
private List<Fragment> getFragments()
{
List<Fragment> fList = new ArrayList<Fragment>();
if(menuInfo.contains("1"))
{
fList.add(TopUpFragment.newInstance(this,"Topup"));
}
if(menuInfo.contains("2"))
{
fList.add(BillPayFragment.newInstance(this,"Billpay"));
}
if(menuInfo.contains("4"))
{
fList.add(VoucherFragment.newInstance(this,"Voucher Sell"));
}
fList.add(MyAccountFragment.newInstance(this,"My Account"));
fList.add(ReportFragment.newInstance(this,"Reports"));
fList.add(SettingsListFragment.newInstance(this,"Settings"));
return fList;
}
#Override
public void onBackPressed()
{
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application" )
.setMessage( "Are you sure you want to Exit" )
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
}
public static View prepareTabView(Context context, String text,int resId) {
View view = LayoutInflater.from(context).inflate(
R.layout.custom_tabview, null);
ImageView iv = (ImageView) view.findViewById(R.id.iv_tabimage);
iv.setImageResource(resId);
TextView tv = (TextView) view.findViewById(R.id.tabIndicatorTextView);
tv.setText(text);
return view;
}
private class ActionBarTabMenuAdapter extends FragmentPagerAdapter {
Activity context;
Context ctx;
ArrayList<String> menuInfo;
private List<Fragment> fragments;
ArrayList<String> services;
ArrayList<Integer> images;
public ActionBarTabMenuAdapter(FragmentManager fm, List<Fragment> fragments,Context ctx,ArrayList<String> servicesName,ArrayList<Integer> servicesImage)
{
super(fm);
this.context=(Activity) ctx;
dataHelper=new DataHelper(ctx);
menuInfo=dataHelper.getTransMenuInfo();
dataHelper.close();
this.services = servicesName;
this.images = servicesImage;
this.fragments = fragments;
menuInfo.add("My Account");
menuInfo.add("Reports");
menuInfo.add("Settings");
System.out.println("## Ctx in ButtonPay==>"+this.context);
}
#Override
public int getCount()
{
return menuInfo.size();
}
#Override
public Fragment getItem(int position) {
System.out.println("position of fragment--"+position);
return this.fragments.get(position);
}
}
class ViewHolder {
TextView Title, Description, ReadMore;
}
public void onClick(View v) {
}
#Override
public void onTabReselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab Reselected method");
}
#Override
public void onTabSelected(Tab tabposition, FragmentTransaction fragmentposition) {
awesomePager.setCurrentItem(tabposition.getPosition());
}
#Override
public void onTabUnselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab unselected method");
System.out.println("tab posiiton in unselected method---"+tabposition.getPosition());
System.out.println("fragment position in unselected method---"+tabposition);
}
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_item_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search for Products");
searchView.setOnQueryTextListener(this);
searchView.setOnSuggestionListener(this);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
Toast.makeText(this, "Suggestion clicked: ",Toast.LENGTH_LONG).show();
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_Home:
startActivityForResult(new Intent(ButtonPayActivity.this,ButtonPayActivity.class), 11);
break;
case R.id.menu_favourite:
finish();
startActivityForResult(new Intent(ButtonPayActivity.this,FavouriteMenuActivity.class), 11);
break;
case R.id.menu_Balance:
new Thread(new GetBalanceInfoRunnable(mContext)).start();
break;
case R.id.menu_logout:
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application")
.setMessage( "Are you sure you want to Logout?")
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
setResult(2);
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
Fragment ::
public class TopUpFragment extends SherlockFragment
{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
LinkedHashMap<String,String>listHeader;
ArrayList<String> topupProSectionID;
ArrayList<String> topupProSectionsName;
ArrayList<TopupProSectionName.Products> listDataChild;
static Context ctx;
static TopUpFragment f ;
private DataHelper dataHelper;
private int lastExpandedPosition = -1;
private ArrayList<TopupProSectionName> mTopupGroupCollection;
public static TopUpFragment newInstance(Activity context,String string)
{
f = new TopUpFragment();
ctx=context;
System.out.println("$$$ onNewInst==>"+ctx);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
//TextView messageTextView = (TextView)v.findViewById(R.id.textView);
//messageTextView.setText(message);
expListView = (ExpandableListView)v.findViewById(R.id.lvExp);
prepareListData();
System.out.println("%%% Ctx==>"+ctx);
return v;
}
private void prepareListData()
{
listHeader = new LinkedHashMap<String, String>();
dataHelper=new DataHelper(ctx);
topupProSectionID=new ArrayList<String>();
listHeader = dataHelper.getSectionSForTopupProduct();
if (listHeader != null)
{
Map.Entry me = null;
Set entrySet = listHeader.entrySet();
Iterator i = entrySet.iterator();
mTopupGroupCollection = new ArrayList<TopupProSectionName>();
TopupProSectionName sectionName = null;
TopupProSectionName.Products topupProduct = null;
while (i.hasNext())
{
sectionName = new TopupProSectionName();
me = (Map.Entry)i.next();
System.out.print("-->"+me.getKey() + ": ");
System.out.println(me.getValue());
sectionName.setsectionName((String)me.getKey());
listDataChild=new ArrayList<TopupProSectionName.Products>();
listDataChild=dataHelper.getFlexiProducts(me.getValue().toString());
listDataChild=dataHelper.getFixProducts(me.getValue().toString(),listDataChild);
System.out.println("Getting products for sys ser ID:"+me.getValue().toString());
//billpayProSectionsName.add((String) me.getKey());
topupProSectionID.add((String) me.getValue());
for(int index=0;index<listDataChild.size();index++)
{
topupProduct = sectionName.new Products();
if(listDataChild.get(index).getSystemServiceID().equals(me.getValue()))
{
topupProduct.setProductName(listDataChild.get(index).getProductName());
topupProduct.setProductID(listDataChild.get(index).getProductID());
sectionName.topupProductList.add(topupProduct);
}
}
mTopupGroupCollection.add(sectionName);
}
}
dataHelper.close();
listAdapter = new ExpandableListAdapter(ctx,mTopupGroupCollection,expListView);
expListView.setAdapter(listAdapter);
}
class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private ArrayList<TopupProSectionName> listDataHeader; // header titles
ArrayList<TopupProSectionName.Products> topupProducts;
private int[] groupStatus;
private ExpandableListView mExpandableListView;
public ExpandableListAdapter(Context context,
ArrayList<TopupProSectionName>sectionName,ExpandableListView pExpandableListView)
{
this._context = context;
this.listDataHeader = sectionName;
this.topupProducts = listDataChild;
mExpandableListView = pExpandableListView;
groupStatus = new int[listDataHeader.size()];
setListEvent();
}
private void setListEvent()
{
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener()
{
public void onGroupExpand(int groupPosition)
{
//collapse the old expanded group, if not the same as new group to expand
//groupStatus[position] = 1;
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition)
{
mExpandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
/*mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener()
{
#Override
public void onGroupCollapse(int position)
{
groupStatus[position] = 0;
}
});*/
mExpandableListView.setOnChildClickListener(new OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
{
String ID=listDataHeader.get(groupPosition).topupProductList.get(childPosition).getProductID();
System.out.println("Product ID in Adapter==>"+ID);
return true;
}
});
}
#Override
public String getChild(int groupPosition, int childPosititon) {
return listDataHeader.get(groupPosition).topupProductList.get(childPosititon).getProductName();
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder childHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item_fragment, null);
childHolder = new ChildHolder();
childHolder.title = (TextView) convertView.findViewById(R.id.lblListItem);
convertView.setTag(childHolder);
}
else
{
childHolder = (ChildHolder) convertView.getTag();
}
childHolder.title.setText(mTopupGroupCollection.get(groupPosition).topupProductList.get(childPosition).getProductName());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mTopupGroupCollection.get(groupPosition).topupProductList.size();
}
#Override
public Object getGroup(int groupPosition) {
return mTopupGroupCollection.get(groupPosition);
}
#Override
public int getGroupCount() {
return mTopupGroupCollection.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
GroupHolder groupHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
groupHolder = new GroupHolder();
groupHolder.title = (TextView) convertView.findViewById(R.id.lblListHeader);
convertView.setTag(groupHolder);
}
else
{
groupHolder = (GroupHolder) convertView.getTag();
}
groupHolder.title.setTypeface(null, Typeface.BOLD);
groupHolder.title.setText(mTopupGroupCollection.get(groupPosition).getsectionName());
return convertView;
}
class GroupHolder {
TextView title;
}
class ChildHolder {
TextView title;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
I am actually getting the action bar in wrong way.
TO use the action bar in each fragment ::
i have placed the setHasOptionsMenu(true); in my onCreate() of fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
After that i am able to use the onCreateOptionMenu() in which i placed the searchview and now i am able to search the date from the expandable listview,getting text from searchview.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
final MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Here");
}
And now m done,Problem resolved.... ;)
I really need your help. First of all I created a Customfragment which extends from SherlockListFragment. I implemented my own Listviewrow design and for this reason I created my own BaseAdapter. A listview row contains a checkbox and some textviews.
My goal was to build a listview which looks and interacts like the Gmail app.
That means if a user clicks on the checkbox the action contextual menu will be activated.
So these are my classes:
public class PurchasesOpenFragment extends SherlockListFragment implements
OnItemClickListener, ListViewContextualMenuListener {
private ActionMode actionMode;
ArrayList<String> purchases = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
purchases.add("Temp 1");
purchases.add("Temp 5");
purchases.add("Temp 2");
purchases.add("Temp 3");
purchases.add("Temp 4");
purchases.add("Temp 6");
purchases.add("Temp 7");
PurchaseOpenAdapter purchaseAdapter = new PurchaseOpenAdapter(
getActivity().getBaseContext(), purchases);
setListAdapter(purchaseAdapter);
purchaseAdapter.setOnListViewContextualMenuListener(this);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast toast = Toast.makeText(getActivity(),
"Show details of element with id: " +arg3,Toast.LENGTH_SHORT);
toast.show();
}
private final class ModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Create the menu from the xml file
MenuInflater inflater = getSherlockActivity()
.getSupportMenuInflater();
inflater.inflate(R.menu.context_test, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here, you can checked selected items to adapt available actions
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// Destroying action mode, let's unselect all items
for (int i = 0; i < getListView().getAdapter().getCount(); i++)
getListView().setItemChecked(i, false);
if (mode == actionMode) {
actionMode = null;
}
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
long[] selected = getListView().getCheckedItemIds();
Toast toast = Toast.makeText(getActivity(), "elements selected: "
+ selected.length, Toast.LENGTH_SHORT);
toast.show();
if (selected.length > 0) {
for (long id : selected) {
toast = Toast.makeText(getActivity(), "element selected with id: " + id,
Toast.LENGTH_SHORT);
toast.show();
}
}
mode.finish();
return true;
}
};
public void closeContextualMenu() {
if (actionMode != null) {
actionMode.finish();
actionMode = null;
}
}
/**
*
*/
#Override
public void onItemCheckBoxChanged(int position, boolean checkState) {
Toast toast = Toast.makeText(getActivity(), "pos: " + position
+ " check: " + checkState, Toast.LENGTH_SHORT);
toast.show();
getListView().setItemChecked(position, checkState);
int amountOfCheckedElements = getListView().getCheckedItemIds().length;
if (amountOfCheckedElements > 0) {
if (actionMode == null) {
actionMode = getSherlockActivity().startActionMode(
new ModeCallback());
}
actionMode.setTitle(amountOfCheckedElements + " selected");
return;
} else {
if (actionMode != null) {
actionMode.finish();
}
}
}
}
2nd class:
public class PurchaseOpenAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private ArrayList<String> purchases;
private static LayoutInflater inflator;
private ListViewContextualMenuListener contextualListener;
public PurchaseOpenAdapter(Context context, ArrayList<String> purchases) {
this.context = context;
this.purchases = purchases;
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return purchases.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
boolean checkBoxChanged = false;
if (convertView == null) {
convertView = inflator
.inflate(R.layout.listview_row, parent, false);
holder = new ViewHolder();
holder.tvDate = (TextView) convertView
.findViewById(R.id.listview_purchase_date);
holder.tvTitle = (TextView) convertView
.findViewById(R.id.listview_purchase_title);
holder.tvSupermarket = (TextView) convertView
.findViewById(R.id.listview_supermarket);
holder.tvArticleAmount = (TextView) convertView
.findViewById(R.id.listview_article_amount);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.listview_checkbox);
holder.checkBox.setTag(position);
holder.checkBox.setOnClickListener(this);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// TODO only temp data
String temp = purchases.get(position);
holder.tvDate.setText("01.01.2001");
holder.tvTitle.setText(temp);
holder.tvSupermarket.setText("Spar");
holder.tvArticleAmount.setText("20 Articles");
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
public void setOnListViewContextualMenuListener(
ListViewContextualMenuListener l) {
contextualListener = l;
}
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Toast toast = Toast
.makeText(context, "Checkboxstate of element with positon: "
+ v.getTag() + " check state: " + cb.isChecked(),
Toast.LENGTH_SHORT);
toast.show();
contextualListener.onItemCheckBoxChanged(Integer
.parseInt(cb.getTag().toString()),
cb.isChecked());
}
static class ViewHolder {
TextView tvDate;
TextView tvTitle;
TextView tvSupermarket;
TextView tvArticleAmount;
CheckBox checkBox;
}
}
As you can see here I used implemented the OnClickMethod for the checkbox in the PurchaseOpenAdapter.
To inform the PurchaseOpenFragment that the state of a checkbox changed I created my own Listener (onItemCheckBoxChanged).
So now i come to describtion of my problem:
I click on the checkbox and the contextual menu appears but checkbox is not checked but if I check the state of the checkbox everything is alright (id and isChecked() are correct).
If I close the contextual menu the checkbox is checked.
If I click on the same checkbox again, the id is completely wrong.
If I remove the listener execution in the adapter class, the checkboxes work correctly.
Hopefully someone can help me. Maybe there is another way to inform the listfragment class.
Thank you in advance!
Since I am a new user I am not allowed to post pictures but I can send them by mail if it is necessary.