Always my last row of database is not showing in alertdialog - android

I am developing a android App where i have to show my data on customize alert dialog from data base. This is my database
I am trying to show all these data on alert-dialog a by follwing code
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG, "Position " + position);
int _id = 0;
int type = getItemViewType(position);
OrderViewHolder orderViewHolder = null;
if (convertView == null) {
orderViewHolder = new OrderViewHolder();
switch (type) {
case TYPE_STATUS:
convertView = inflater.inflate(R.layout.category_header, null);
orderViewHolder.setTvTitle((TextView) convertView
.findViewById(R.id.category));
break;
case TYPE_ITEM:
convertView = inflater.inflate(R.layout.order_list_row, null);
orderViewHolder.setTvTitle((TextView) convertView
.findViewById(R.id.orderTitle));
orderViewHolder.setTvPrice((TextView) convertView
.findViewById(R.id.orderPrice));
orderViewHolder.setIvDelete((ImageButton) convertView
.findViewById(R.id.deleteOrder));
// orderViewHolder.setIvDelete((ImageButton)convertView.findViewById(R.id.deleteOrder).setLayoutParams(params))
break;
}
convertView.setTag(orderViewHolder);
} else {
orderViewHolder = (OrderViewHolder) convertView.getTag();
}
if (position == 0) {
if (starterCount != 0) {
orderViewHolder.getTvTitle().setText("");
// orderViewHolder.getTvTitle().setBackgroundDrawable(R.drawable.tab_starters_menu_on);
orderViewHolder.getTvTitle().setTextColor(R.color.Black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT_BOLD);
orderViewHolder.getTvTitle().setBackgroundResource(R.drawable.tt111);
orderViewHolder.getTvTitle().setHeight(20);
orderViewHolder.getTvTitle().setWidth(100);
/*
* RestaurantHome.setFontTextViewTahoma(OrderListAdapter,
* orderViewHolder.getTvTitle());
*/
}
else {
orderViewHolder.getTvTitle().setText(" ");
orderViewHolder.getTvTitle().setBackgroundColor(Color.WHITE);
}
}
if ((position !=0))
{
System.out.println(" position vlue : "+position);
if (oStarterCursor.moveToPosition(position-1)) {
String title = oStarterCursor.getString(oStarterCursor.getColumnIndex("item_name"));
System.out.println( " value of title "+title);
String price = oStarterCursor.getString(oStarterCursor.getColumnIndex("Item_cost"));
System.out.println( " value of price "+price);
_id = oStarterCursor.getInt(oStarterCursor
.getColumnIndex("_id"));
if (title != null) {
title = title.trim();
orderViewHolder.getTvTitle().setText(title);
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(Gravity.CENTER_VERTICAL);
}
if (price != null) {
price = price.trim();
orderViewHolder.getTvPrice().setText(price + ".00");
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(Gravity.CENTER_VERTICAL);
}
_id = oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
}
convertView.setTag(R.id.orderTitle, _id);
if (orderViewHolder.getIvDelete() != null) {
orderViewHolder.getIvDelete().setTag(R.id.orderTitle, _id);
}
// _id =
// oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
}
//}
return convertView;}
I am going to post my order_list_row.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100sp"
android:layout_height="fill_parent"
android:background="#fff" >
<ImageButton
android:id="#+id/deleteOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:background="#fff"
android:onClick="clickHandler"
android:src="#drawable/icon_close" >
</ImageButton>
<TextView
android:id="#+id/orderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="4sp"
android:background="#fff"
android:textColor="#000"
android:textSize="16dp" >
</TextView>
<TextView
android:id="#+id/orderPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4sp"
android:layout_toLeftOf="#id/deleteOrder"
android:layout_toRightOf="#id/orderTitle"
android:background="#fff"
android:textColor="#000"
android:textSize="16dp" >
</TextView>
</RelativeLayout>
But it is not showing my last data in my database.
As you can see by my screen shot last data is not showing form database. Why fanta is not showing ? Always last row is showing in alertdialog from database.What is logical issue in my code i can't understand ? Most probably it is mistake of my logic but where it is i can't find . I hope i am able to explain my problem to all my well-wisher . Please help me . Thanks in advance to all

i would like to know why are u passing position -1 as param to movetoPosition method
just pass position ..
i think according to your approach last element is never being read !!

Finally i solve my issue. Thanks to all who suggest me to solve this issue.
public int getCount() {
// TODO Auto-generated method stub
Log.d(TAG, "GetCount "+starterCount);
return starterCount +1 ;
}
And
if ((position !=0)&& (position != starterCount + 1))
{
// TODO Auto-generated method stub
}

Related

ImageView not updated in ItemList

I am trying to update the image inside ItemList, I am using the below method
This is how I am getting ImageView 'imgView' Object using the below methods -
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONParsingMainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
if(markedQuestion != null){
try {
JSONObject jsonObj = new JSONObject(markedQuestion);
JSONArray contacts = jsonObj.getJSONArray("data");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String questionid = c.getString("questionid");
System.out.println("Question No :" + i + "Question Id is :" + questionid);
Long itemId = lv.getItemIdAtPosition(Integer.parseInt(questionid));
System.out.println("Item Id xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxasdasd" + itemId);
changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv);
imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId);
imgView.setImageResource(R.drawable.cancel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mp.start();
position++;
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("position", Integer.toString(position));
context.startActivity(intent);
}
});
}
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
This code is not updating the cancel image in the list item, when I debug I am getting correct id (i.e. 'imageViewstickId' as shown in XML), but the image is not updating, nor giving any error
imgView.setImageResource(R.drawable.cancel);
My XML code also -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/cardViewQuestionId"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="15dp"
card_view:cardElevation="2dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingTop="6dp"
android:text="test"
android:textColor="#color/gradientStart"
android:textSize="16sp"
android:textStyle="bold"
/>
<ImageView
android:id="#+id/imageViewstickId"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
/>
</LinearLayout>
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/gradientStop" />
<TextView
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
I have tried everything modifying the code, etc. but nothing works for me
Any help shall be appreciated, thanks
Edits - (Added Debug screen Shot) Please check in debug window, CardViewId is same as XML ImageView id... Still not updating
Solution:
Instead of this:
imgView.setImageResource(R.drawable.cancel);
write:
imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel));
Try it. Let's hope it works.
You can simply use this:
If you are in Activity then use this
int id = getResources().getIdentifier("cancel","drawable", getPackageName());
Or in Fragment
int id = context.getResources().getIdentifier("cancel","drawable", context.getPackageName());
// "cancel" drawable resource name
// "drawable" drawable directory
This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following
imgView.setImageResource(id);
hope this will work.
There are two best solutions for that:-
1) Instead of using this
imgView.setImageResource(R.drawable.cancel);
Use This Method:-
imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel));
2)Using Glide Library
https://bumptech.github.io/glide/doc/download-setup.html
Your id is correct still it is not updating then it might be a problem that your Resource file (R.java) is not updating try cleaning your project and then check.
If this not works you can also try following code:-
Resources resources = getResources();
imgView.setImageDrawable(resources.getDrawable(R.drawable.cancel));
May be helpful for others to think this way -
I got Clue from this post - how to know when listview is finished loading data on android
My data may be getting updated, but the list was not fully loaded and thats why the data is over writing. I used the following code , thanks for the actual user who posted the above answer
lv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
Log.d(TAG, "list got updated, do what ever u want");
if(markedQuestion != null){
try {
JSONObject jsonObj = new JSONObject(markedQuestion);
JSONArray contacts = jsonObj.getJSONArray("data");
for (int x = 0; x < contacts.length(); x++) {
JSONObject c = contacts.getJSONObject(x);
String questionid = c.getString("questionid");
System.out.println("Question No :" + x + "Question Id is :" + questionid);
System.out.println(getResources());
changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv);
imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId);
// imgView.setImageResource(R.drawable.cancel);
imgView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.cancel));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});

ListView not refreshing after updating object in the list

I've an ArrayList containing Cards. I'm trying to edit a Cards tag in the ArrayList and after editingit I want the ListView to refresh, so the user can see the updated Card, with the new tag.
I'm using cardslib for my Cards. And I'm using Android TagView Lib to tag my cards.
Here's the XML for the Card
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/colorBorder"
android:layout_width="10dp"
android:layout_height="#dimen/card_base_empty_height"
android:layout_marginTop="2dp"
android:background="#drawable/rectangle" />
<TextView
(...) />
<TextView
(...) />
<TextView
(...) />
<TextView
(...) />
<pl.charmas.android.tagview.TagView
android:id="#+id/tags_view"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="#id/card_main_inner_simple_total_contacts"
android:layout_marginLeft="10dp"
android:layout_alignParentRight="true"
android:textSize="12sp"/>
</RelativeLayout>
And here's when I try to edit and update the list view:
private final OnClickCardHeaderPopupMenuListener popupMenuListener = new OnClickCardHeaderPopupMenuListener() {
#Override
public void onMenuItemClick(BaseCard baseCard, MenuItem menuItem) {
final String backupId = baseCard.getId();
switch (menuItem.getItemId()) {
case R.id.action_restore:
BackupsIntentService.restoreCloudBackup(getActivity(), backupId);
Log.d(TAG, "Going to update the card");
setCurrentTask(backupId, "Restoring...", "");
break;
case R.id.action_download:
BackupsIntentService.downloadCloudBackup(getActivity(), backupId);
break;
case R.id.action_delete:
BackupsIntentService.removeCloudBackup(getActivity(), backupId);
break;
}
}
};
And here's the setCurrentTask method, where I update and refresh the list:
private void setCurrentTask(final String backupId, final String currentTaskDescription, final String separator)
{
int pos = -1;
for(int i = 0; i<cloudBackupCardList.size(); i++)
{
BackupCard backupCard = (BackupCard) cloudBackupCardList.get(i);
if(backupCard.getId().equals(backupId))
{
pos = i;
Log.d(TAG, "Found the card at position: " + i + " updating it now");
TagView.Tag[] tags = {new TagView.Tag(currentTaskDescription, Color.BLUE)};
backupCard.setCurrentTaskDescription(tags, separator);
}
}
if(pos == -1)
return;
BackupCard backupCard = (BackupCard) cloudBackupCardList.get(pos);
Log.d(TAG, "There should be: " + currentTaskDescription + " but found: " + backupCard.getCurrentTaskDescription() + " Thread: " + Thread.currentThread()
.getName());
cardListView.setAdapter(new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
// remoteCardArrayMultiChoiceAdapter.remove(remoteCardArrayMultiChoiceAdapter.getItem(pos));
// remoteCardArrayMultiChoiceAdapter.insert(backupCard, pos);
//
//// remoteCardArrayMultiChoiceAdapter.clear();
//// remoteCardArrayMultiChoiceAdapter.addAll(cloudBackupCardList);
// remoteCardArrayMultiChoiceAdapter.notifyDataSetChanged();
// cardListView.refreshDrawableState();
}
I've tried all those (the commented ones) different methods and the list is still not updated.
Here's my logcat output:
07-07 15:12:59.644: D/CardCloudBackupsFragment(24311): Going to update the card
07-07 15:12:59.644: D/CardCloudBackupsFragment(24311): Found the card at position: 8 updating it now
07-07 15:12:59.656: D/CardCloudBackupsFragment(24311): There should be: Restoring... but found: RESTORING... ThreaD: main
As you can see from the logcat, the object is updated but in the listview, on my terminal, it is not. Which leads me to conclude that the listview is not updated/refreshed. (Dont mind the all upper case letters in Restoring, it's expected.)
////////////////////// EDIT ////////////////////////////////
Here is my setupInnerViewElements method as requested in the comments box.
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
//Retrieve elements
titleTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_title);
subTitleTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_sub_title);
TextView descriptionTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_description);
TextView totalContactsTextView = (TextView) parent.findViewById(R.id.card_main_inner_simple_total_contacts);
tagView = (TagView) parent.findViewById(R.id.tags_view);
if(isLocal)
{
if (titleTextView != null)
titleTextView.setText(TIMESTAMP_TXT + titleCard); // 1st
if (subTitleTextView != null)
subTitleTextView.setText(CONTACTS_COUNT_TXT + subTitleCard); // 2nd
if(descriptionTextView != null)
descriptionTextView.setText(RESTORE_COUNT_TXT + description); // 3rd
if(tagView != null)
{
TagView.Tag[] tags = {new TagView.Tag("Wow", Color.TRANSPARENT)};
tagView.setTags( tags, "" );
}
return;
}
if (titleTextView != null)
titleTextView.setText(TIMESTAMP_TXT + titleCard); // 1st
if (subTitleTextView != null)
subTitleTextView.setText(PHONE_BRAND_TXT + subTitleCard); // 2nd
if(descriptionTextView != null)
descriptionTextView.setText(PHONE_MODEL_TXT + description); // 3rd
if(totalContactsTextView != null)
totalContactsTextView.setText(CONTACTS_COUNT_TXT + contactsNumber); // 4th
if(tagView != null)
{
TagView.Tag[] tags = {new TagView.Tag("Wow", Color.TRANSPARENT)};
tagView.setTags( tags, "" );
}
}
Replace below Line:
cardListView.setAdapter(new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
with
RemoteCardArrayMultiChoiceAdapter adapter=new RemoteCardArrayMultiChoiceAdapter(getActivity(), cloudBackupCardList));
cardListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Thats it...
The problem was a no problem at all, it was as simply as setting the tag and the TagsLibrary would take care of updating the CardView. I just didn't know this so I was trying to refresh the listview.
So I simply have this method on my card class:
public void setCurrentTaskDescription(TagView.Tag[] tags, String separator)
{
tagView.setTags(tags, separator);
}
and then on my listener I just do this:
switch ( menuItem.getItemId()) {
case R.id.action_restore:
BackupsIntentService.restoreCloudBackup(getActivity(), backupId);
EventBus.getDefault().post(new
setCurrentTask(backupCard, "Restoring...", "");
break;
}
private void setCurrentTask(final BackupCard backupCard, final String currentTaskDescription, final String separator)
{
TagView.Tag[] tags = {new TagView.Tag(currentTaskDescription, Color.GREEN)};
backupCard.setCurrentTaskDescription(tags, separator);
}
No need to refresh the list!
I was trying to make a thunderstorm inside a glass of water. Lesson learned.

getView() is not working as i supposed

I am going to develop a APP where i am using customize alert dialog. Data have come from database to this alert-dialog.
menu_to_showdialogCursor = dh.rawQuery("SELECT _id ,item_name,Item_cost FROM order_customer WHERE item_name LIKE ? AND Item_cost LIKE ?", new String[]{"%","%"});
OrderListAdapter orderAdapter = new OrderListAdapter(MainScreen.this,menu_to_showdialogCursor );
orderList.setAdapter(orderAdapter);
ABove line is calling my Adapter class.Now i ma going to show my getView() in adapter class
public View getView(int position, View convertView, ViewGroup parent) {
OrderViewHolder orderViewHolder = null;
if (convertView == null) {
orderViewHolder = new OrderViewHolder();
convertView = inflater.inflate(R.layout.order_list_row, null);
orderViewHolder.setTvTitle((TextView) convertView
.findViewById(R.id.orderTitle));
orderViewHolder.setTvPrice((TextView) convertView
.findViewById(R.id.orderPrice));
orderViewHolder.setIvDelete((ImageButton) convertView
.findViewById(R.id.deleteOrder));
convertView.setTag(orderViewHolder);
} else {
orderViewHolder = (OrderViewHolder) convertView.getTag();
}
if (position != 0)
{
System.out.println(" value of position :"+position);
List lit = new ArrayList();
List litp = new ArrayList();
// System.out.println(" value of postion of cursor : ");
OrderViewHolder odr_obj = null;
if (oStarterCursor.moveToFirst()) {
do{
odr_obj = new OrderViewHolder();
title = oStarterCursor.getString(oStarterCursor.getColumnIndex("item_name"));
System.out.println("value of title :"+title);
lit.add(title);
price = oStarterCursor.getString(oStarterCursor.getColumnIndex("Item_cost"));
System.out.println("value of price :"+price);
litp.add(price);
}while(oStarterCursor.moveToNext());
}
// _id = oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
if (title != null) {
title = title.trim();
Iterator it = lit.iterator();
while (it.hasNext()) {
int i =0;
//System.out.println(" data iterator "+it.next().toString());
String test =it.next().toString();
System.out.println(" iterator vavue :"+test);
orderViewHolder.getTvTitle().setText(test);
}
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(
Gravity.CENTER_VERTICAL);
}
if (price != null) {
price = price.trim();
orderViewHolder.getTvPrice().setText(price + ".00");
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(
Gravity.CENTER_VERTICAL);
}
//_id = oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
//convertView.setTag(R.id.orderTitle, _id);
if (orderViewHolder.getIvDelete() != null) {
//orderViewHolder.getIvDelete().setTag(R.id.orderTitle, _id);
}
}
return convertView;}
Problem is that in my data base there is two row as in below image..
But in my alert dialog only showing one row twice. I did not get where is logical mistake.For conveniences i am going to show my screen-shot
So Where is problem i can't get please some body help me take out of this problem.
I think it's your line :
if (position != 0)
The first line of an adapter is 0 so it will not set the data for the first line of data.
I believe its because you are using getView wrong, getView does not just get called once it gets called many times. you are looping through your cursor each time getView is called so you are only displaying the last item in the cursor after you loop through your 2 lists.
if you are getting data from a cursor you should be using SimpleCursorAdapter and then override bindView and just use the cursor variable in the method each time its called
Edit
basically along the lines of this
oStarterCursor.moveToPosition(position);
orderViewHolder.getTvTitle().setText(oStarterCursor.getString(oStarterCursor.getColumnIndex("item_name")));
is all you need to get the data really

ListView item background changes depending on scroll position

I'm running into a very strange ListView behaviour. I have a simple chat application which uses a ListView and a custom implementation of BaseAdapter to show messages.
The idea I had was to shade messages from the "local" user grey and have messages from the "remote" user white, to help the user distinguish between the two.
The two screenshots below show what's happening. The second is the exact same activity, xml etc etc, simply scrolled down a bit.
Scrolled up:
Scrolled down:
Look at the message sent by "Me" # 23:05. When at the top it has no contrast to its neighbours, but when it is scrolled to the bottom, the difference is clear to see.
This occurs on a nexus 4 and 7 on 4.2.2, and a GS3 running 4.1.2.
Here is the XML for one of the ListView items:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_view_conversation_message_list_item_wrapper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingLeft="5dp"
android:paddingRight="10dp" >
<ImageView
android:id="#+id/activity_view_conversation_message_list_item_user_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:src="#drawable/default_user_image" />
<TextView
android:id="#+id/activity_view_conversation_message_list_item_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="1dp"
android:layout_toRightOf="#+id/activity_view_conversation_message_list_item_user_image"
android:text="Martyn"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/activity_view_conversation_message_list_item_contents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/activity_view_conversation_message_list_item_heading"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_marginTop="2dp"
android:layout_toLeftOf="#+id/activity_view_conversation_message_list_item_ack"
android:layout_toRightOf="#+id/activity_view_conversation_message_list_item_user_image"
android:text="Hello this is some text"
android:textColor="#333333"
android:textIsSelectable="true"
android:textSize="18sp" />
<TextView
android:id="#+id/activity_view_conversation_message_list_item_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="2dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="2dp"
android:text="12:08"
android:textSize="14sp" />
<ImageView
android:id="#+id/activity_view_conversation_message_list_item_ack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/activity_view_conversation_message_list_item_time"
android:layout_marginRight="2dp"
android:layout_marginTop="8dp"
android:layout_toLeftOf="#+id/activity_view_conversation_message_list_item_time"
android:src="#drawable/red_dot_8dp" />
</RelativeLayout>
And here is where I set the colour of the RelativeLayout:
if(localUserId.equals(remoteUserId)){
itemLayout.setBackgroundColor(Color.parseColor("#F9F9F9"));
}
That code runs inside the getView() method of my Adapter.
I've Googled this a fair bit and turned up nothing, there are a lot of SO questions regarding the android:cacheColorHint issue but I don't think that is what is going on here.
Has anyone run into this before? I'm stumped!
EDIT: Here's the baseadapter code:
public class MessageListAdapter extends BaseAdapter {
private ArrayList<Message> messageList;
Context context;
/**
* Constructor
* #param newConversationsList An ArrayList of Conversation objects that this adapter will use
* #param newContext The context of the activity that instantiated this adapter
*/
MessageListAdapter(ArrayList<Message> newMessageList, Context newContext){
messageList = newMessageList;
//reload();
context = newContext;
}
public int getCount() {
return messageList.size();
}
public Object getItem(int position) {
return messageList.get(position);
}
public long getItemId(int position) {
return position;
}
/**
* Adds a message to the chat list
* #param message A Message object containing all the message's information
*/
public void add(Message message){
//nMessagesToShow++; //A new message has been added, so increase the number to show by one
Log.d(TAG, "COUNT: "+getCount());
//refresh();
}
public void refresh(){
this.notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view!=null){
//return view;
}
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Get the Message object from the list
Message message = messageList.get(position);
//Get the data from the message
String senderId = message.getFromUser();
int messageType = message.getType();
String senderFirstName;
ImageView userImage, messageImage;
TextView messageHeading, messageBody;
switch(messageType){
case Message.MESSAGE_TYPE_TEXT: //Standard text message
//The layout we inflate for this list item will vary depending on whether this message has the same sender as the previous
if(position>0 && senderId.equals(messageList.get(position-1).getFromUser())){ //True if this is not the first message AND the sender id matches that of the previous message
view = vi.inflate(R.layout.activity_view_conversation_message_list_item_alternate, null); //Inflate an alternate version of the list item which has no heading or user image
}
else{ //This is the first message OR the sender id is different to the previous
view = vi.inflate(R.layout.activity_view_conversation_message_list_item, null); //Inflate the standard version of the layout
userImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_user_image);
messageHeading = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_heading);
//Use the sender's ID to get the sender's image and first name
Contact contact = database.getContact(senderId);
if(senderId.equals(localUserId)){ //True if the local user sent this message
senderFirstName = "Me";
}
else{
senderFirstName = contact.getFirstName();
}
userImage.setImageBitmap(contact.getImageBitmap(100, 100, 6));
messageHeading.setText(senderFirstName);
}
messageBody = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_contents);
messageBody.setText(message.getContents(null));
break;
case Message.MESSAGE_TYPE_IMAGE: //Image message
view = vi.inflate(R.layout.activity_view_conversation_message_list_item_image, null); //Inflate a list item template for displaying an image
userImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_user_image);
//Sender's first name
messageHeading = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_heading);
Contact contact = database.getContact(senderId);
if(senderId.equals(localUserId)){ //True if the local user sent this message
senderFirstName = "Me";
}
else{
senderFirstName = contact.getFirstName();
}
messageHeading.setText(senderFirstName);
messageImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_image);
String imageResourceId = null;
//The message is a JSON object containing several fields, one of which is the file name which we will use to get the image
try {
JSONObject messageJSON = new JSONObject(message.getContents(null));
String imagePath = Environment.getExternalStorageDirectory()+"/epicChat/resources/"+messageJSON.getString("fileName");
int imageWidth = messageJSON.getInt("width"); //We want the dimensions in order to calculate the aspect ratio of the image
int imageHeight = messageJSON.getInt("height");
if(messageJSON.has("resourceId")){
imageResourceId = messageJSON.getString("resourceId"); //This is used when opening the image gallery
}
int displayWidth = 300;
int displayHeight = (int) ((float) imageHeight / (float) imageWidth * (float) displayWidth);
String imagePathFull = imagePath+displayWidth+displayHeight; //For the caching
Bitmap originalImage = null;
//Check the bitmap cache exists. If not, reinstantiate it
if(MainActivity.bitmapCache==null){ //Cache is null
MainActivity.loadBitmapCache();
}
else{ //Cache is not null, so check it to see if this image is in it
originalImage = MainActivity.bitmapCache.get(imagePathFull);
}
if(originalImage==null){ //True if the bitmap was not in the cache. So we must load from disk instead
new Utils.LoadBitmapAsync(imagePath, messageImage, displayWidth, displayHeight, MainActivity.bitmapCache).execute();
messageImage.getLayoutParams().height = displayHeight;
}
else{
messageImage.setImageBitmap(originalImage);
}
}
catch (JSONException e) {
Log.e(TAG, "Error reading image JSON: "+e.toString());
}
if(imageResourceId!=null){ //Only attach the listener if we got a valid resource ID
final String recourceIdFinal = imageResourceId;
final String conversationIdFinal = message.getUserList();
messageImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent showConversationImageGalleryIntent = new Intent(context, ViewConversationImageGalleryActivity.class);
showConversationImageGalleryIntent.putExtra("conversationId", conversationIdFinal);
showConversationImageGalleryIntent.putExtra("resourceId", recourceIdFinal);
startActivityForResult(showConversationImageGalleryIntent, ACTION_SHOW_CONVERSATION_IMAGE_GALLERY);
}
});
}
userImage.setImageBitmap(contact.getImageBitmap(100, 100, 6));
break;
case Message.MESSAGE_TYPE_INVALID:
default:
break;
}
//Some layout items are present in all layouts. Typically these are the status indicator and the message time
RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.activity_view_conversation_message_list_item_wrapper);
//If the message is from the local user, give it a subtle grey background
if(localUserId.equals(message.getFromUser())){
itemLayout.setBackgroundColor(Color.parseColor("#E9E9E9"));
}
else{
itemLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
TextView messageTimeText = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_time);
messageTimeText.setText(message.getFormattedTime());
ImageView messageStatusImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_ack);
//Set the status image according to the status of the message
switch(message.getStatus()){
case Message.MESSAGE_STATUS_PENDING: //Pending messages should have a red dot
messageStatusImage.setImageResource(R.drawable.red_dot_8dp);
messageStatusImage.setVisibility(View.VISIBLE);
break;
case Message.MESSAGE_STATUS_ACK_SERVER: //Messages that reached the server should have an orange dot
messageStatusImage.setImageResource(R.drawable.orange_dot_8dp);
messageStatusImage.setVisibility(View.VISIBLE);
break;
case Message.MESSAGE_STATUS_ACK_RECIPIENT: //Messages that reached the recipient should have an green dot
messageStatusImage.setImageResource(R.drawable.green_dot_8dp);
messageStatusImage.setVisibility(View.VISIBLE);
break;
case Message.MESSAGE_STATUS_NOT_SET: //Not set typically means the message came from another user, in which case the status image should be hidden
default: //Also default here
messageStatusImage.setVisibility(View.INVISIBLE);
break;
}
return view;
}
}
Since there's no else statement matching your if, this is probably due to view recycling. When an item from a ListView scrolls off the screen, the operating system removes it and hands it back to the adapter in the same state it was removed. This means you need to set the background color when it's not the local user's message as well.

Creating a New Button in existing Source Code? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
http://www.itechcode.com/2012/03/18/create-calculator-in-android-programming/
Im using his source code but it seems very different than the "Beginner Level" Programming I have been use to i.e. creating new project, modifying layout, referencing in main.java, etc.
I'm trying to use his source code and modify/create new operations and maybe add a activity. I would usually know how to do most of that stuff if it wasn't laid out differently. Thank You!
package com.pragmatouch.calculator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;
public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;
Stack<String> mInputStack;
Stack<String> mOperationStack;
KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;
String mDecimalSeperator;
double memoryValue = Double.NaN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);
// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();
// Process keypad button
ProcessKeypadInput(keypadButton);
}
});
mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();
int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;
switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;
int endIndex = currentInputLen - 1;
// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal seperator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}
mInputStack.add(text);
mOperationStack.add(text);
dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);
resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;
mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case PRGM:
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}
private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}
private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}
private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;
String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);
double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
String resultStr = doubleToString(result);
if (resultStr == null)
return null;
mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}
return resultStr;
}
private String doubleToString(double value) {
if (Double.isNaN(value))
return null;
long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}
private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);
} catch (NumberFormatException nfe) {
}
return result;
}
private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}
ENUM:
package com.pragmatouch.calculator;
public enum KeypadButton {
MC("MC",KeypadButtonCategory.MEMORYBUFFER)
, MR("MR",KeypadButtonCategory.MEMORYBUFFER)
, MS("MS",KeypadButtonCategory.MEMORYBUFFER)
, M_ADD("M+",KeypadButtonCategory.MEMORYBUFFER)
, M_REMOVE("M-",KeypadButtonCategory.MEMORYBUFFER)
, BACKSPACE("<-",KeypadButtonCategory.CLEAR)
, CE("CE",KeypadButtonCategory.CLEAR)
, C("C",KeypadButtonCategory.CLEAR)
, ZERO("0",KeypadButtonCategory.NUMBER)
, ONE("1",KeypadButtonCategory.NUMBER)
, TWO("2",KeypadButtonCategory.NUMBER)
, THREE("3",KeypadButtonCategory.NUMBER)
, FOUR("4",KeypadButtonCategory.NUMBER)
, FIVE("5",KeypadButtonCategory.NUMBER)
, SIX("6",KeypadButtonCategory.NUMBER)
, SEVEN("7",KeypadButtonCategory.NUMBER)
, EIGHT("8",KeypadButtonCategory.NUMBER)
, NINE("9",KeypadButtonCategory.NUMBER)
, PLUS(" + ",KeypadButtonCategory.OPERATOR)
, MINUS(" - ",KeypadButtonCategory.OPERATOR)
, MULTIPLY(" * ",KeypadButtonCategory.OPERATOR)
, DIV(" / ",KeypadButtonCategory.OPERATOR)
, RECIPROC("1/x",KeypadButtonCategory.OTHER)
, DECIMAL_SEP(",",KeypadButtonCategory.OTHER)
, SIGN("±",KeypadButtonCategory.OTHER)
, SQRT("SQRT",KeypadButtonCategory.OTHER)
, PERCENT("%",KeypadButtonCategory.OTHER)
, CALCULATE("=",KeypadButtonCategory.RESULT)
, PRGM("PRGM",KeypadButtonCategory.PRGM)
, DUMMY("",KeypadButtonCategory.DUMMY);
CharSequence mText; // Display Text
KeypadButtonCategory mCategory;
KeypadButton(CharSequence text,KeypadButtonCategory category) {
mText = text;
mCategory = category;
}
public CharSequence getText() {
return mText;
}
}
package com.pragmatouch.calculator;
public enum KeypadButtonCategory {
MEMORYBUFFER
, NUMBER
, OPERATOR
, DUMMY
, CLEAR
, RESULT
, OTHER
, PRGM
}
I have a great answer for you. I recently wanted to create my own button in android but I wanted to do it in a simple way. Follow these steps and in a few minutes I will post pictures.
1) create a new layout. start with a LinearLayout. Nest a FramedLayout and another LinearLayout inside of it.
2) then add a TextView to it. This is where practice makes perfect. Play around with the attributes. Learn what they do. when you have the general information of how you want your button to be display go to the next step.
3) what your are going to do is include this in another view as a button. You can use a specific attribute to make it look like a button as well.
Give me a few minutes and I will post some code and a picture.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/CBN_LinearLayout"
style="#android:style/Widget.Button"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/CBV_texview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:gravity="right"
android:text="#string/checkorder"
android:textColor="#color/Black" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" >
<ImageView
android:id="#+id/CBV_imageView1"
android:layout_width="23dp"
android:layout_height="15dp"
android:layout_gravity="center_vertical"
android:contentDescription="#string/redcirclenotify"
android:src="#drawable/rednotify"
android:visibility="visible" />
<TextView
android:id="#+id/CBV_textview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dp"
android:gravity="left"
android:text="#string/zero"
android:visibility="visible" />
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/CBV_textview3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fadingEdge="horizontal"
android:gravity="center_horizontal"
android:text="#string/blankstring" />
<TextView
android:id="#+id/CBV_textview4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="#string/blankstring" />
</LinearLayout>
when you add it to another view as a button you use:
<include
android:id="#+id/MI_checkorder"
style="android:buttonStyle"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:layout_marginTop="5dp"
android:layout_weight="1"
layout="#layout/custombtnview"
android:background="#style/AppTheme"
android:clickable="true"
android:focusable="true" />
The important part of this is setting the Style for the root LinearLayout to #android:style/Widget.Button
Once this is done it will look like a button and work like a button.
Below is an image of the final product:
another part of your question. Adjust sizes of standard buttons in android:
1) almost everything can be controled with how you use the XML. This can all be controled in the area to right, in the ADK. These attributes help you to control almost every aspect.
for example as in the calculator...
you have 4 buttons in a row so you want to add 4 buttons inside of a horizontal LinearLayout. Then you can give the a weight of 1 for each button then set their Width to FillParent. This will auto size the buttons to be displayed in the width of the screen equally.
Am I better off making my own calc or modify the existing code?
I would never tell someone to recreate the wheel, however, if you do not understand the code well enough to pickup where they left off then this can be an uphill struggle for you. Your best bet if you are having trouble understanding the code given to you or how to modify it, would be to actually post the code in another question and be very specific and ask for example how can I change what this particular button displays and what the result of clicking it would be. This forum depends on the people asking the questions to be clear and concise. If not then questions will closed as fast as they are opened. Generalizations are severely frowned upon on the site.
In the end, what I am trying to do is make my own scientific calculator but I don't want to spend extra time doing the simple operations.
The best way to answer this is to take a look at how the calculator is assembled in the GUI or Graphical Layout. Try changing a button and what it does. for example make the plus a minus just for the learning curve.
1) look for , PLUS(" + ",KeypadButtonCategory.OPERATOR) and notice that is a string for plus. change it to " T " see if it changes in the app. If it does then go into the code. In the code you will find case CALCULATE: for for the = sign in the ENUM and then inside that you find evalResult = evaluateResult(true);. If you follow this you reach:
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
so now you can change result = leftVal + rightVal; to result = leftVal - rightVal; and you have just changed it. so it will take some time to understand the code but you have to do some trial and error to understand it. I hope this helps answer your question.

Categories

Resources