Getting the value of clicked buttons and append them - android

I'm newbie in android development and going to create simple drag'n'Drop calculator.
My goal is to make buttons from 0 to 9 and create numbers by clicking them.
For example:
0 1 2 3 4 5 6 7 8 9
and by clicking them create number 245, then drag this number, for example, into the sum mark +, then repeat second number and automatically retrieve results.
First, I'll show my code now...
MainActivity.java
package com.coreprojects.calculator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
TextView calc_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// This method comes from XML button = buttonClick
public void buttonClick(View v) {
// Textarea where numbers will be shown
TextView TV = (TextView) findViewById(R.id.calc_cache_1);
// Get the ID of buttons
Button calc_btn_1 = (Button) findViewById(R.id.button1);
Button calc_btn_2 = (Button) findViewById(R.id.button2);
// INT type numbers convert to string, because of [setText]
String buttonText_1 = calc_btn_1.getText().toString();
String buttonText_2 = calc_btn_2.getText().toString();
// Result as text
TV.setText(buttonText_1); // first number is not shown
TV.setText(buttonText_2); // second number
// alert
/**
String pressed = "Operation Done";
new AlertDialog.Builder(this).setTitle("result").setMessage(pressed)
.setNeutralButton("Done", null).show();
*/
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/calc_cache_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/main_text" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:clickable="true"
android:onClick="buttonClick"
android:text="#string/button_1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="64dp"
android:clickable="true"
android:onClick="buttonClick"
android:text="#string/button_2" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Calculator</string>
<string name="main_text"></string>
<string name="menu_settings">Settings</string>
<string name="button_1">1</string>
<string name="button_2">2</string>
</resources>
Now problem...
When i click on buttons, any time result shows number 2, because i think
TV.setText(buttonText_2) is second command and first one is not read any more.
I tried to write together, like TV.setText(buttonText_1 + buttonText_2), but now it results 12, even if i click any single button...
so how can I append numbers by clicking them? and also, if u see here, i have clickable button in XML, and get ID of pressed button, but i want it to be more dynamic.
For example: when i press button, don't get the ID of it, but simply identify the button ID and get value. i can show u simple analog in jQuery:
$(".button_class_not_ID").click(
var elementValue = $(this).html();
or
var elementValue = $(this).attr("id");
console.log(elementValue);
);

Related

Retrieving and sending a Textview value from/to a Server

I have an app with a button and also a textview (Numeric ex . 100)
i am click button then increment Textview (value) +5.
I am trying to send the value to Php Table Row and Also Retrieve Table Row Data in Same Text View.
in app was close and Open then fetch PHP Data(server) as per Texview
my_table
id
user_Name
amount
MyActivity.java
public class MainActivity extends AppCompatActivity {
int minteger = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void increaseInteger(View view) {
minteger = minteger + 5 ;
display(minteger);
}
private void display(int number) {
TextView displayInteger = (TextView) findViewById(
R.id.integer_number);
displayInteger.setText("Integer: " + number);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click the plus button to increase integer number" />
<TextView
android:id="#+id/integer_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:textSize="30sp"
android:text="Integer: 0" />
<Button
android:id="#+id/increase"
android:onClick="increaseInteger"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INCREASE" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="bottom"
android:textSize="20sp"
android:text="viralandroid.com"/>
</LinearLayout>
Initialize the TextView & your Button inside onCreate first and remove the initialization from display method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayInteger = (TextView) findViewById(
R.id.integer_number);
Button myButton = (Button) findViewById(
R.id.yourButtonId);
// Here you'll need onClickListener for the button to handle if button clicked, increase the number and etc or calling methods.
}
Follow Android Button Onclick for handle Android Button click.
But, the point is, if you add onClickListener to the Button, you may call display or just the setText inside onClickListener and no need for another method.(Simplifying)
Also add:
TextView displayInteger;
In above of onCreate to have access all over the Activity and the current class.
To send string to server side, follow this link : How send data to website by using android app
You'll need to first get the text by getText().toString() then sending as string to server: How to get EditText value and display it on screen through TextView?

Android using if statement on textview and imagebutton

Hello guys i am making simple game that can take point if i click right button.
so there is 5 imagebutton and 1 textview. textview will generate random number 1-5 . and those 5 imagebuttons has 5 different id , so my point is if textview generates 1 number how can i check it its right button using if statement.
if ( textview(current generated number ) == imagebutton(id) ) {
counter++)
something like this can you help me guys? example code would be nice :D
Set the tag value for the buttons
either from xml set Tag attribute
Tag = "1"
or
btn.setTag("1");
Add the buttons corresponding value to its tag and then compare it with tags value
in onClick method you get id of button clicked
Button btn = (Button) findViewById(id);
string valu = btn.getTag();
Now compare the textView value with this tag value.
string txt = textView.getText();
if(txt.equals(valu))
{
// do what you want
}
You could store the button resource IDs an array of int. Then in a common click handler, you could test whether the button clicked was the same as the one randomly selected. Here's a simplistic, minimal example. It assumes you've set and displayed the random number before you get the button clicks.
In your class, define these fields:
private int myButtons[] = null;
private int randomNumber = 0;
In onCreate(), add the following:
myButtons = new int[] {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4};
Add the method:
public btnClick(View v) {
if (findViewById(myButtons[randomNumber]) == v)
Log.i(TAG, "Correct!");
else
Log.i(TAG, "Incorrect!");
}
Then in your layout XML, define the buttons with your click handler:
<Button
android:id="#+id/btn0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn0" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn1" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn2" />
<Button
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn3" />
<Button
android:id="#+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn4" />

Android: Unable to Prevent buttons from increasing size and overlapping with other buttons

I am new to Android Programming, what I am trying to do in this Android Application is to create a xml page filled with buttons.
When I click the button, the button would change to light green color and when I click it again, it would change to light grey
The error: I am getting is when I click the button, it increases in size and overlaps with the other buttons, please help me out here, it is not user friendly in this case
attached below is the code:
lockerbooking.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/sisButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="#string/sis"
/>
<Button
android:id="#+id/solButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/soeButton"
android:layout_alignBottom="#+id/soeButton"
android:layout_alignParentRight="true"
android:text="#string/sol" />
<Button
android:id="#+id/soeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/sisButton"
android:layout_alignBottom="#+id/sisButton"
android:layout_centerHorizontal="true"
android:text="#string/soe" />
</RelativeLayout>
Code:
makeBooking.java
public class makeBooking extends Activity {
Button sisButton;
Button solButton;
Button soeButton;
Button sobButton;
super.onCreate(savedInstanceState);
// Get the message from the intent
setContentView(R.layout.lockerbookpage);
Intent intent = getIntent();
// Initialize TextViews
sisButton = (Button) findViewById(R.id.sisButton);
solButton = (Button) findViewById(R.id.solButton);
soeButton = (Button) findViewById(R.id.soeButton);
sobButton = (Button) findViewById(R.id.sobButton);
}
public OnClickListener solButtonListener = new OnClickListener(){
boolean flag = true;
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(flag){
solButton.setBackgroundColor(Color.GREEN);
}
else{
solButton.setBackgroundColor(Color.LTGRAY);
}
flag=!flag;
}
};
...The code goes on
Please help me out here, I am eager to learn
to avoid overlapping of buttons, use fixed width and height for buttons:
change this:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
to some this like this:
android:layout_width="100dp" //what ever size suits your layout
android:layout_height="50dp" //fixing this,will not overlap the buttons

Force close error on setOnClickListener (Example from hello Android book section 3.5)

I am having problem in starting a new activity on clicking a button, here's my code:
package test.project;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
public class TestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View aboutButton = findViewById(R.id.about_content);
aboutButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_content:
Intent i = new Intent(this, testit.class);
startActivity(i);
break;
// More buttons go here (if any) ...
}
}
}
Can anyone please help me correct this error
Error Line
aboutButton.setOnClickListener(this);
Main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" android:layout_gravity="center"
android:text="Click here" android:layout_gravity="center" android:layout_marginTop="30dip"/>
</LinearLayout>
XML file containing about_content is
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip" >
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
</ScrollView>
about_content is already defined here
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
Well, you didn't post your logcat output, but since this is such a common beginner's mistake, I'm going to take a wild guess and say that you are probably getting a NullPointerException.
Your call to findViewById is probably returning null, which means that the system could not find the view associated with the id given by R.id.about_content. I would double check your XML layout for typos.
Odds are you don't have anything with the id about_content in main.xml, which will create a NullPointerException.
Also, if aboutButton is supposed to be a traditional Button, then you should use this:
Button aboutButton = (Button) findViewById(R.id.about_content);
Addition
Since aboutButton is a TextView, use this:
TextView aboutButton = (TextView) findViewById(R.id.about_content);
but this TextView must be in the layout passed to setContentView() or findViewById() will return null.
That is because the "main.xml" which you have set your content view ... does not contain the about_content TextView, its in the other xml which you have posted ...
Note: You can access only those R.id's which are present in your setContentView(R.layout.yourlayout) xml ...
you make setContentView(R.layout.main); but main.xml does not include View have id = R.id.about_content. If you raplace by findViewById(R.id.button1); It will work.
This is the solution for
Button aboutButton = (Button)findViewById(R.id.about_content);
And dont forget to add testit Activity in Android Manifest

Android page control like iPhone page control

I would like to put something back to this VERY helpful site, so this is not really a question, but rather my solution to this issue. I would also add that this solution was gleaned form support from this site and many others, so it represents the combined efforts of many other developers. To them I say thank you!
The QUESTION is "How can you recreate the horizontal scrollView aspects of iPhone apps and the associated page control in the Android environment?"
This arose because I wanted to display the steps in recipe, the associated method fro each step and the necessary ingredients in a single scroll view. I also wanted a page control to display to the user where they were in the steps and allow them to move to any specific step
This part of my app displays the steps in a recipe. Each step appears on a page and has three components. A step identifier(ie. STEP 1, STEP 2), a method and a ingredients required for the step.
Below the recipe section we display a page control that show which page is active and can be used to navigate to specific pages. You will notice that the page control has image buttons and the two images are simple circles, one for the non selected page (page.png) and one for the selected page (page_selected.png)
When the activity is created the steps for the selected recipe are retrieved from the data and the scroller section created by adding a view for each step in the recipe. When you swipe the scroller the view snaps to the next or previous page and the pager display is updated to indicate which page you are on
First 3 xml layouts (res/layout)
recipe.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!--Scroller section-->
<HorizontalScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="320dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="100dp" >
<LinearLayout
android:id="#+id/methodScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<!-- pager section -->
<LinearLayout
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="430dp"
android:gravity="center"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
recipesscroll.xml (the view that will be added to the scroller section for each recipe step. Note that the scroller section has a onTouchlistner in recipeViewController.java to handle page scrolling)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recipeScroll"
android:layout_width="320dp"
android:layout_height="320dp"
android:gravity="center_vertical" >
<TextView
android:id="#+id/method"
style="#style/scrollMethod"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:text="Method" />
<TextView
android:id="#+id/ingredients"
style="#style/scrollIngredients"
android:layout_width="wrap_content"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:text="Ingredients" />
<TextView
android:id="#+id/methodStep"
style="#style/scrollStep"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignParentTop="true"
android:text="Step" />
</RelativeLayout>
recipiespager.xml ( the view that will be added to the pager section for each recipe step. Note that each of these will have a onClick event in recipeViewController.java that will scroll to the specific page selected in the pager control)
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/pageButton"
android:layout_marginLeft="10dp"
android:layout_width="16dp"
android:layout_height="16dp"
android:onClick="selectPage">
</Button>
This is all brought together in recipeViewController.java
//my package name change this to yours
package com.infactdata.spinAdinner;
import java.util.ArrayList;
//DataModel is the model for my data change this to yours or ignore
because it is just away of holding the data that will populate the views
import com.infactdata.plist.DataModel;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class RecipeViewController extends RootViewController {
private DataModel currentData;
HorizontalScrollView h_scroll;
int numberOfPages = 0;
int thePage;
int otherPage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//first of the xml files
setContentView(R.layout.recipe);
//reference to my global variables
GlobalClass global = (GlobalClass)getApplicationContext();
//because I wanted a particular type face
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/trebucit.ttf");
//VERY IMPORTANT because we need to use this to add the content to the scroll
and pager sections
LayoutInflater inflater = getLayoutInflater();
//current data held a dataModel
currentData = global.getCurrent();
currentName.setText(currentData.getName());
String imageFile = currentData.getImage();
Resources r = getResources();
int res = r.getIdentifier(imageFile, "drawable", "com.infactdata.spinAdinner");
image.setImageResource(res);
//recources that change the pager indicators to different images
thePage = r.getIdentifier("page_selected", "drawable","com.infactdata.spinAdinner");
otherPage = r.getIdentifier("page", "drawable", "com.infactdata.spinAdinner");
//Get the method(ArrayList) out of the currentData(DataModel). This is the array of
data that will fill the added view with different content (ie. the specific
instructions for the recipe step. This could be your own data array.
ArrayList<String[]> method = new ArrayList<String[]>();
method = currentData.getMethod(0);
numberOfPages = method.size();
//now to build the views by adding the content and then adding the text for that
content that reflects the instructions for the step in the recipe
for( int i = 0; i < method.size(); i++){
String[] methodStep = method.get(i);
//find the scroll view
LinearLayout scroll = (LinearLayout) findViewById(R.id.methodScrollView);
//find the recipe scroller. the second xml file
RelativeLayout step = (RelativeLayout)findViewById(R.id.recipeScroll);
//add the recipe step (step) to the scrollview (scroll)
step = (RelativeLayout)inflater.inflate(R.layout.recipescroll, scroll, false);
//add the instructions for this step in the recipe
TextView stage = (TextView)step.findViewById(R.id.methodStep);
stage.setText(methodStep[0].toString());
stage.setTypeface(face);
TextView methodText = (TextView)step.findViewById(R.id.method);
methodText.setText(methodStep[1].toString());
methodText.setTypeface(face);
TextView ingredients = (TextView)step.findViewById(R.id.ingredients);
ingredients.setText(methodStep[2].toString());
ingredients.setTypeface(face);
//create method step and add to scroll
scroll.addView(step);
//pager setup is a duplicate of the above
//find the pager
LinearLayout pager = (LinearLayout) findViewById(R.id.pager);
//find the pager button. the third xml file
Button page = (Button)inflater.inflate(R.layout.recipespager, pager, false);
//give each button it own ID. This will be used to test which button should be highlighted and used to move to a specific page. This is because the ID is equal to the page number (0 based of course)
page.setId(i);
//because this is a fresh construction we will be on page 0 so highlight that button
if (i == 0){
page.setBackgroundResource(thePage);
}
//create page control and add to pager
pager.addView(page);
}
//create the onTouch controls
h_scroll = (HorizontalScrollView) findViewById(R.id.scroll_view);
h_scroll.setOnTouchListener(scrolling);
}
private OnTouchListener scrolling = new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() ==
MotionEvent.ACTION_CANCEL ){
int scrollX = h_scroll.getScrollX();
int itemWidth = h_scroll.getMeasuredWidth();
int activePage = ((scrollX + itemWidth / 2) / itemWidth);
int scrollTo = activePage * itemWidth;
h_scroll.smoothScrollTo(scrollTo, 0);
//page control display the active page button
Log.v("MyDebug","Active page = "+activePage);
for(int i = 0; i < numberOfPages; i++){
Button aPage = (Button) findViewById(i);
if(i == activePage){
aPage.setBackgroundResource(thePage);
}else{
aPage.setBackgroundResource(otherPage);
}
}
return true;
} else {
return false;
}
}
};
//this is the onClick handler for the page buttons and moves the scroller to the page
associated with the button. That is through the button ID, which matches the page
number (0 based of course
public void selectPage(View v) {
int newPage = v.getId();
int itemWidth = h_scroll.getMeasuredWidth();
int scrollTo = newPage * itemWidth;
h_scroll.smoothScrollTo(scrollTo, 0);
//page control display
Log.v("MyDebug","Active page = "+newPage);
for(int i = 0; i < numberOfPages; i++){
Button aPage = (Button) findViewById(i);
if(i == newPage){
aPage.setBackgroundResource(thePage);
}else{
aPage.setBackgroundResource(otherPage);
}
}
}
public void finishActivity(View v){
//perform back action
finish();
}
public void nextActivity(View v){
//move to next activity
}
}
Well that was my solution. I am certain that there are much clever programers than me out there so I am sure someone can improve this. Anyhow THANKS stackoverflow!!!!
I think the GreenDroid library will help achieve something similar to the iPhone's UIPageControl.
Have a look at their app in marketplace GDCatalog. Also you can extract the files you want and make the pagecontrol. I've used it in my app and it works fine. Needs a bit optimisation to make it smoother.
https://github.com/cyrilmottier/GreenDroid

Categories

Resources