Android: different theme when using PopupWindow in Listview - android

I've got a custom listview inside a fragment that inflates a PopupWindow whenever an message is clicked.
However I can't seem to figure out why the buttons in the list-view header are using a different theme/style than the normal rows in the listview. Can someone please care to explain?
List-view item:
List-view header:
This is how i inflate the toolbar:
popup = new PopupWindow(inflater.inflate(R.layout.message_tool, null, false));
popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setOutsideTouchable(true);
Rect location = locateView(v);
popup.showAtLocation(v, Gravity.NO_GRAVITY, location.left, location.top - 200);
QuestionFragment.java
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.fragment_question, container, false);
final ListView messages = (ListView)view.findViewById(R.id.messages);
messages.setDivider(null);
// Add question (header)
View headerView = inflater.inflate(R.layout.messages_question, null);
MessageModel messageItem = new MessageModel();
messageItem.message = question.getQuestion();
messageItem.id = question.getId();
messageItem.gender = question.getGender();
messageItem.name = question.getName();
LinearLayout messageBackground = (LinearLayout)headerView.findViewById(R.id.messageBackground);
TextView message = (TextView)headerView.findViewById(R.id.question);
int bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
messageBackground.setBackground(ContextCompat.getDrawable(getActivity().getApplicationContext(), bgDrawable));
messages.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
SingleInstancePopup.GetInstance().hidePopup();
}
});
messageBackground.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(getClass().getName(), "Clicked on question");
SingleInstancePopup popup = SingleInstancePopup.GetInstance();
if(popup.getPopup() != null) {
popup.hidePopup();
} else {
popup.showPopup(inflater, v);
}
}
});
message.setText(messageItem.message);
messages.addHeaderView(headerView, null, false);
// Add footer
View footerView = inflater.inflate(R.layout.messages_footer, null);
messages.addFooterView(footerView, null, false);
messagesAdapter = new MessagesAdapter(getActivity().getApplicationContext());
messages.setAdapter(messagesAdapter);
final Handler handler_ = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE_UI) {
QuestionModel question = (QuestionModel) msg.obj;
for (AnswerModel answer : question.getAnswers()) {
MessageModel messageItem = new MessageModel();
messageItem.message = answer.getComment();
messageItem.id = answer.getId();
messageItem.gender = answer.getGender();
messageItem.name = answer.getName();
messageItem.reply = (answer.getParentId() > 0);
messagesAdapter.add(messageItem);
}
ProgressBar progress = (ProgressBar) messages.findViewById(R.id.messagesProgress);
if (progress != null) {
progress.setVisibility(View.GONE);
}
messagesAdapter.notifyDataSetChanged();
}
}
};
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
QuestionModel q = QuestionModel.getById(question.getId());
handler_.sendMessage(Message.obtain(handler_, UPDATE_UI, q));
} catch (Exception e) {
Log.d(getClass().getName(), "Failed to load question", e);
}
}
});
thread.start();
return view;
}
MessagesAdapter.java
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final MessageModel messageItem = this.getItem(position);
View v;
int bgDrawable;
if(messageItem.reply) {
v = inflater.inflate(R.layout.messages_answer_reply, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_right_states : R.drawable.bubble_blue_right_states;
} else {
v = inflater.inflate(R.layout.messages_answer, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
}
LinearLayout messageBackground = (LinearLayout)v.findViewById(R.id.messageBackground);
TextView message = (TextView)v.findViewById(R.id.comment);
messageBackground.setBackground(ContextCompat.getDrawable(getContext(), bgDrawable));
message.setText(messageItem.message);
messageBackground.setClickable(true);
messageBackground.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(getClass().getName(), "Pressing down on message");
SingleInstancePopup popup = SingleInstancePopup.GetInstance();
if(popup.getPopup() != null) {
popup.hidePopup();
} else {
popup.showPopup(inflater, v);
}
}
});
return v;
}
Thanks!
- Simon

In MessagesAdapter.java, inflater doesn't have your activity's theme, that's why your buttons look different. Instead of getting the system inflater service, pass the activity's layout inflater to your adapter, like this:
QuestionFragment.java
messagesAdapter = new MessagesAdapter(getActivity().getApplicationContext(), getActivity().getLayoutInflater());
MessagesAdapter.java
private LayoutInflater inflater;
public MessagesAdapter(Context context, LayoutInflater inflater) {
super(context, 0);
this.inflater = inflater;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final MessageModel messageItem = this.getItem(position);
View v;
int bgDrawable;
if (messageItem.reply) {
v = inflater.inflate(R.layout.messages_answer_reply, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_right_states : R.drawable.bubble_blue_right_states;
} else {
v = inflater.inflate(R.layout.messages_answer, null, false);
bgDrawable = (messageItem.gender > 1) ? R.drawable.bubble_red_left_states : R.drawable.bubble_blue_left_states;
}
// .......
return v;
}

Related

Why memory keeps increasing when you scroll in a List on Android

I am watching the monitor on Android and I notice that the memory keeps increasing when you scroll down and up.
I am using an Adaper. It's supposed to reuse the views, but it seems that it doesn't work.
As you can see in the images below the memory starts at 9.94 MB and I could increase it at 25.82 MB just by scrolling down and up.
You can see the code that I use.
public class ListMainFragment
extends Fragment
implements LoaderManager.LoaderCallbacks<List<Earthquake>> {
public ListMainFragment() {
// Required empty public constructor
}
ListView listView;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.fragment_mainlist, container, false);
final ArrayList<Earthquake> earthquake =
(ArrayList<Earthquake>) new EarthquakeController(new EarthquakesJson()).getListOfEarthquakes();
listView = (ListView)viewRoot.findViewById(R.id.list_view);
EarthquakeAdapter noteAdapter = new EarthquakeAdapter(getActivity(), earthquake);
listView.setAdapter(noteAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//final String mensaje = notas.get(position).getMag();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(earthquake.get(0).getMapURL()));
Log.w("ListView", "Se despliega la siguente URL " + earthquake.get(0).getMapURL());
startActivity(intent);
}
});
return viewRoot;
}
}
The Adapter:
public class EarthquakeAdapter extends ArrayAdapter <Earthquake> {
public EarthquakeAdapter(Context context, ArrayList<Earthquake> notas) {
super(context, 0, notas);
}
private static final String LOCATION_SEPARATOR = " of";
View view;
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
*/
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
Log.w("AppList", "converView es null");
}
Earthquake note = getItem(position);
Date dateObject = new Date(note.getTimeInMilliseconds());
TextView locationOffset = (TextView)convertView.findViewById(R.id.listItem_tv_locationOffset);
TextView place = (TextView)convertView.findViewById(R.id.listItem_tv_place);
TextView date = (TextView)convertView.findViewById(R.id.lisItem_tv_date);
TextView time = (TextView)convertView.findViewById(R.id.lisItem_tv_time);
TextView mag = (TextView) convertView.findViewById(R.id.listItem_tv_mag);
GradientDrawable magnitudCicle = (GradientDrawable) mag.getBackground();
magnitudCicle.setColor(getMagnitudColor(note.getMag()));
String str_locationOffset, str_place;
if (note.getPlace().contains(LOCATION_SEPARATOR)) {
String [] locations = note.getPlace().split(LOCATION_SEPARATOR);
str_locationOffset = locations[0];
str_place = locations[1];
}
else {
str_place = note.getPlace();
str_locationOffset = getContext().getString(R.string.near_the);
}
mag.setText( new DecimalFormat("0.0").format(note.getMag()));
date.setText(formatDate(dateObject));
place.setText(str_place);
time.setText(formatTime(dateObject));
locationOffset.setText(str_locationOffset);
/* final String mensaje = title.getText().toString();
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),mensaje,Toast.LENGTH_SHORT).show();
}
});*/
return convertView;
}
}
You should use Recycler View for better performance.
From: https://developer.android.com/training/material/lists-cards.html

Android Inflating multiple layouts inside a fragment

I am working in a fragment. When the fragment is called it inflates a layout. Which all works.
v = createTreeView( inflater, container, savedInstanceState);
On my action bar I have a search button which Onclicks changes the layout
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
Both views work separately, but when I move the createFilterListView to the OnClick functions it does nothing. The Log has been processed which means it is running through. It just is not inflating the layout.
Below is the onCreateView
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
linflate = inflater;
VContainer = container;
m_Context = inflater.getContext();
thisApp = (ThisApp)getActivity().getApplicationContext();
v = createTreeView( inflater, container, savedInstanceState);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_search);
ImageButton btnSearch = (ImageButton)d.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
View b = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_cancel_search);
ImageButton btnCancelSearch = (ImageButton)b.findViewById(R.id.btn_cancel_search);
btnCancelSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createTreeView( linflate, VContainer, savedInstanceState);
}
});
return v;
}
Any help would be greatly appreciated. Thank you in advance.
private View createFliterLivstView( LayoutInflater inflater, ViewGroup container){
View v1 = linflate.inflate(R.layout.list_main, VContainer, false);
historyContainer = (FrameLayout)v1.findViewById(R.id.history_container_layout);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.txtSearch);
EditText filterEditText = (EditText)d.findViewById(R.id.txtSearch);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("anish", s.toString());
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf(s.toString()) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(getActivity().getBaseContext(), R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
#Override
public void onInflate(ViewStub stub, View inflated) {
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
return v1;
}
Below is the CreateTreeView
private View createTreeView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout_list_symptoms, container, false);
makeList();
Button btnNext = (Button)v.findViewById(R.id.btn_next);
btnNext.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String bsafe = thisApp.app_pref.getString("BSAFE", "0");
if(bsafe==null || bsafe.equalsIgnoreCase("0")) {
thisApp.app_edit.putString("SYMTOMS", "");
thisApp.app_edit.commit();
}
Set<Long> sel = fancyAdapter.selected;
Iterator<Long> it = sel.iterator();
boolean hasDone = false;
int i = 0;
while(it.hasNext()) {
Long longId = it.next();
//Log.i(TAG, "...id = " + longId);
final Integer[] hierarchy = fancyAdapter.getManager().getHierarchyDescription(longId);
// 5678
WorkVO vo = list.get(longId.intValue());
try {
pnObj.put("value" , jsonArr.put(vo.getName()) );
//i++;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hasDone = true;
}
jsonSymptoms.put(pnObj);
Log.i("Symtoms ", " json="+ jsonSymptoms.toString());
thisApp.app_edit.putString("SYMTOMS", jsonSymptoms.toString());
thisApp.app_edit.commit();
if(hasDone) {
if(bsafe!=null && bsafe.equalsIgnoreCase("1")) {
mCallback.onNextWork(DefinedConstants.FRAG_BSAFE_REPORT);
} else {
mCallback.onNextWork(DefinedConstants.FRAG_FATIGUE_RATING);
}
} else {
Toast.makeText(getActivity(), "Please make a selection", 0).show();
}
}
});
TreeType newTreeType = null;
boolean newCollapsible;
if (savedInstanceState == null) {
manager = new InMemoryTreeStateManager<Long>();
final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
for (int i = 0; i < NODES.length; i++) {
treeBuilder.sequentiallyAddNextNode((long) i, NODES[i]);
}
//Log.d(TAG, manager.toString());
newTreeType = TreeType.FANCY;
newCollapsible = true;
} else {
manager = (TreeStateManager<Long>) savedInstanceState
.getSerializable("treeManager");
if (manager == null) {
manager = new InMemoryTreeStateManager<Long>();
}
newTreeType = (TreeType) savedInstanceState
.getSerializable("treeType");
if (newTreeType == null) {
newTreeType = TreeType.SIMPLE;
}
newCollapsible = savedInstanceState.getBoolean("collapsible");
}
treeView = (TreeViewList) v.findViewById(R.id.mainTreeView);
fancyAdapter = new FancyColouredVariousSizesAdapter(getActivity(), selected,
manager, LEVEL_NUMBER, job_kind, list);
simpleAdapter = new SimpleStandardAdapter(getActivity(), selected, manager,
LEVEL_NUMBER, job_kind, list);
setTreeAdapter(newTreeType);
setCollapsible(newCollapsible);
registerForContextMenu(treeView);
manager.collapseChildren(null);
return v;
}
Inflate a view with this method.
View v = View.inflate(m_context,R.layout.yourlayout,null);
The createView method returns a View which sets the view for the fragment. What you are doing in the onClick is creating a view that isn't overriding your fragments main view.
To be honest it would be much easier and would require less state logic if on click you replaced the Fragment with a new Fragment with the layout you wanted.
Having a Fragment that handles two separate layouts is harder to maintain and to keep the correct state. Not to mention will make the class much larger.

Get the total count of number of rows in the Custom Listview Android

I am trying to getting the total Count of the getView custom listview. But want to display in the different layout. Here is my onCreatedView. I am not sure how to inflate the layout. Thanks for all your help.
private static ListView addDropListView = null;
private TransactionAddDropAdapter addDropAdapter = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentPendingTrades = inflater.inflate(R.layout.fragment_transactions_pending, container, false);
pendingTradesView = inflater;
return fragmentPendingTrades;
}
public void onViewCreated(final View view, final Bundle savedInstanceState) {
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
this.emptyTransationsContainer = view.findViewById(R.id.transactions_pending_transactions_emptyContainer);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
}
Here is my Holderview that get the getView
public class TransactionAddDropAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private List<TransactionAddDrop> addDropList = new ArrayList<TransactionAddDrop>();
public TransactionAddDropAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
public void setAddDropList(List<TransactionAddDrop> addDropList) {
clearAddDropList();
for (TransactionAddDrop ad : addDropList) {
if (ad.isStateApprove()) {
this.addDropApprovalsList.add(ad);
} else {
this.addDropList.add(ad);
}
}
}
public void clearAddDropList() {
this.addDropList.clear();
this.addDropApprovalsList.clear();
}
#Override
public int getCount() {
int size = this.addDropList.size();
if (this.addDropApprovalsList.size() > 0) {
size += 1;
}
return size;
}
#Override
public Object getItem(int position) {
try {
if (this.addDropList == null) {
return null;
} else if (position < addDropList.size()) {
return this.addDropList.get(position);
} else {
return this.addDropApprovalsList;
}
} catch (Exception e) {
return null;
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final TransactionAddDrop addDropData = this.addDropList.get(position);
TransactionAddDropViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.fragment_pending_transaction_list_item, null);
holder = new TransactionAddDropViewHolder();
holder.withdrawButton = convertView.findViewById(R.id.pendingTransactionItem_withdrawButton);
holder.addContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_addContainer);
holder.dropContainer = (LinearLayout) convertView.findViewById(R.id.pendingTransactionItem_dropContainer);
holder.rootView = convertView.findViewById(R.id.swipeRight);
holder.swipeButtons();
convertView.setTag(holder);
} else {
holder = (TransactionAddDropViewHolder) convertView.getTag();
holder.swipeButtons();
}
}
Ok, I "think" I know what's going on here. You setup your ListView and add its TransactionAddDropAdapter, and then set the total amount of items.
this.addDropListView = (ListView) view.findViewById(R.id.transactions_pending_transactionsListView);
this.addDropAdapter = new TransactionAddDropAdapter(pendingTradesView);
this.addDropListView.setAdapter(this.addDropAdapter);
TextView getTotalCount = (TextView) view.findViewById(R.id.transactions_pending_TransactionsAddDropCount);
getTotalCount.setText(""+addDropListView.getCount());
However, at this point, you haven't called setAddDropList(List<TransactionAddDrop> addDropList) on addDropAdapter, so addDropList in getCount() is still an empty array, so getCount() == 0, which is why you are seeing 0 being displayed.
So, you need to find where you call addDropAdapter.setAddDropList() and then call getTotalCount.setText(""+addDropListView.getCount()); right after in order to update the total number of rows.

How to inflate inflate two layouts from same class?

I have a ListView and I want to display the selected list content in a popup when I click on it in the view. How can I do this?
Here's my code:
public class EventbyDate extends ListActivity {
Context cont;
private Runnable DateEventListThread;
public String DateEventListThreadResponse;
private ProgressDialog m_ProgDialog = null;
public DateEventListAdapter DateEventList_adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventsbydate);
GetDateEventList();
this.DateEventList_adapter = new DateEventListAdapter(this,R.layout.eventsbydate_list,
RoamMeo_Config.DateEventList);
setListAdapter(this.DateEventList_adapter);
}
#Override
public void onPause() {
super.onPause();
this.finish();
}
void GetDateEventList() {
m_ProgDialog = ProgressDialog.show(EventbyDate.this, " Please wait",
"Collecting Data..", true);
DateEventListThread = new Runnable() {
#Override
public void run() {
DateEventListThread = null;
try {
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(returnResponse);
}
};
Thread thread = new Thread(null, DateEventListThread, "DateEventListThread");
thread.start();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
LayoutInflater inflater = (LayoutInflater) EventbyDate.
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup,null,
false),300,400,true);
pw.showAtLocation(findViewById(R.id.txt_start_date),
Gravity.CENTER, 0,0);
}
private Runnable returnResponse = new Runnable() {
#Override
public void run() {
try {
if (DateEventListThreadResponse != null&&
DateEventListThreadResponse.length() > 0) {
boolean check =
XMLParsing.EventDate_List_Response(DateEventListThreadResponse);
if(check) {
DateEventList_adapter.notifyDataSetChanged();
} else {
Toast msg =
Toast.makeText(EventbyDate.this,"No list... ",Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER,
msg.getXOffset() / 2,msg.getYOffset() / 2);
msg.show();
}
}
if (m_ProgDialog != null)
m_ProgDialog.dismiss();
m_ProgDialog = null;
} catch (Exception e) {
if (m_ProgDialog != null)
m_ProgDialog.dismiss();
m_ProgDialog = null;
}
}
};
class DateEventListAdapter extends ArrayAdapter<SaveDateEventList> {
ArrayList<SaveDateEventList> items;
public DateEventListAdapter(Context context, int
textViewResourceId,
ArrayList<SaveDateEventList> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
View v = convertView;
final SaveDateEventList d = items.get(position);
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.eventsbydate_list, null);
}
if (!items.isEmpty()) {
if (d != null) {
TextView start_date = (TextView)
v.findViewById(R.id.txt_start_date);
start_date.setText(d.ev_start_date);
TextView start_time = (TextView)
v.findViewById(R.id.txt_start_time);
start_time.setText(d.ev_start_time);
TextView poptext = (TextView)
v.findViewById(R.id.poptext);
poptext.setText(d.ev_start_time);
}
}
return v;
}
}
}
You can do something like this, protected void onListItemClick(ListView l, View v, int position, long id) {YourObject o = l.getItemAtPosition(position);}. After that you have to set what ever you need to display in your pop-up screen via this obtained object.

Tab Application Development

I wish to create a tab application in Android.
I wish to basically have four tabs in my application.
Namely, Home, Compose, Inbox, Sent.
I started with a TabContainer extending TabActivity, is this a correct approach.
Since i will be having MenuItem, which i used be having multiple views for Inbox, as such List of inbox, i sud be able to read, and then delete and all.
I wish to know how do I approach?
Basically i wish to make an application similar to gmail.
Any ideas, or direction might help me
public class Inbox extends ListActivity{
private ProgressDialog progressDialog = null;
private ArrayList<EmailElement> emailElement = null;
private InboxAdapter inboxAdapter;
private CheckBoxWithInboxList newInboxAdapter;
private Runnable beforeFetchingEmail;
private TextView emailFromTextView = null;
private TextView emailSubjectTextView = null;
ListView listView;
private static int mode = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox);
mode = this.getIntent().getIntExtra("EDIT_MODE", -1);
Log.i("EDITMODE", String.valueOf(mode));
emailElement = new ArrayList<EmailElement>();
if(mode ==0 || mode==-1){
this.inboxAdapter = new InboxAdapter(this, R.layout.inbox_row, emailElement);
setListAdapter(inboxAdapter);
}else{
this.newInboxAdapter = new CheckBoxWithInboxList(this, R.layout.inbox_row, emailElement);
setListAdapter(newInboxAdapter);
}
beforeFetchingEmail = new Runnable() {
#Override
public void run() {
getEmails();
}
};
Thread thread = new Thread(null, beforeFetchingEmail, "MagentoBackground");
thread.start();
progressDialog = ProgressDialog.show(Inbox.this,"Please wait...",
"Retrieving Emails ...", true);
listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView, View view,
int position, long id) {
}
});
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(emailElement != null && emailElement.size() > 0){
if(mode==0 || mode==-1){
inboxAdapter.notifyDataSetChanged();
for(int i=0;i<emailElement.size();i++){
inboxAdapter.add(emailElement.get(i));
}
progressDialog.dismiss();
inboxAdapter.notifyDataSetChanged();
}else{
newInboxAdapter.notifyDataSetChanged();
for(int i=0;i<emailElement.size();i++){
newInboxAdapter.add(emailElement.get(i));
}
progressDialog.dismiss();
newInboxAdapter.notifyDataSetChanged();
}
}
}
};
private void getEmails(){
try{
emailElement = new ArrayList<EmailElement>();
EmailElement ee0 = new EmailElement();
ee0.setFrom("Robin Thapa");
ee0.setSubject("Urgent Meeting");
emailElement.add(ee0);
EmailElement ee1 = new EmailElement();
ee1.setFrom("Deepak Thapa");
ee1.setSubject("Staff meeting #Sunday");
emailElement.add(ee1);
Thread.sleep(5000);
}catch(Exception ex){
}
runOnUiThread(returnRes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.inbox_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.inboxEdit:
Intent intent = new Intent(this,EmailClient.class);
intent.putExtra("tabId", 2);
intent.putExtra("EDIT_MODE", 1);
startActivityForResult(intent, Intent.FILL_IN_DATA);
return true;
case R.id.inboxRefresh:
return true;
case R.id.inboxNext:
return true;
case R.id.inboxPrevious:
return true;
}
return false;
}
private class InboxAdapter extends ArrayAdapter<EmailElement>{
private ArrayList<EmailElement> items;
public InboxAdapter(Context context,int textViewResourceId,
ArrayList<EmailElement> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.inbox_row, null);
}
EmailElement o = items.get(position);
if (o != null) {
CheckBox emailCheckBox = (CheckBox)view.findViewById(R.id.inboxCheckBoxId);
emailCheckBox.setVisibility(View.INVISIBLE);
emailFromTextView = (TextView) view.findViewById(R.id.inboxEmailFrom);
emailSubjectTextView = (TextView) view.findViewById(R.id.inboxEmailSubject);
if (emailFromTextView != null){
emailFromTextView.setText("From: "+o.getFrom());
}
if(emailSubjectTextView != null){
emailSubjectTextView.setText("Sub: ["+ o.getSubject()+"]");
}
}
return view;
}
}
private class CheckBoxWithInboxList extends ArrayAdapter<EmailElement>{
private ArrayList<EmailElement> items;
public CheckBoxWithInboxList(Context context,int textViewResourceId,
ArrayList<EmailElement> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.inbox_row, null);
}
EmailElement o = items.get(position);
if (o != null) {
CheckBox emailCheckBox = (CheckBox)view.findViewById(R.id.inboxCheckBoxId);
emailCheckBox.setVisibility(View.VISIBLE);
emailFromTextView = (TextView) view.findViewById(R.id.inboxEmailFrom);
emailSubjectTextView = (TextView) view.findViewById(R.id.inboxEmailSubject);
if (emailFromTextView != null){
emailFromTextView.setText("From: "+o.getFrom());
}
if(emailSubjectTextView != null){
emailSubjectTextView.setText("Sub: ["+ o.getSubject()+"]");
}
}
return view;
}
}
}
For tablayout I recommend : http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
you might want to read up on this Tab Layout | Android Development
it's a good starting point

Categories

Resources