I'm a new android developer and I decided to create a simple test app that has 6 editViews and calculates the average of those numbers inputted.
I am looking to find out how to create the views programmatically when needed instead of wasting resources on having all of the views there OnCreate.
I've been searching around but have been unable find out how to implement it. If someone could help out that would be great.
Thanks!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
average = (TextView)findViewById(R.id.average);
edit_message = (EditText)findViewById(R.id.edit_message);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
editText4 = (EditText)findViewById(R.id.editText4);
editText5 = (EditText)findViewById(R.id.editText5);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = edit_message.getText().toString();
s2 = editText.getText().toString();
s3 = editText2.getText().toString();
s4 = editText3.getText().toString();
s5 = editText4.getText().toString();
s6 = editText5.getText().toString();
if(!s1.isEmpty()) {
n1 = Integer.parseInt(s1);
counter++;
}
if(!s2.isEmpty()) {
n2 = Integer.parseInt(s2);
counter++;
}
if(!s3.isEmpty()) {
n3 = Integer.parseInt(s3);
counter++;
}
if(!s4.isEmpty()) {
n4 = Integer.parseInt(s4);
counter++;
}
if(!s5.isEmpty()) {
n5 = Integer.parseInt(s5);
counter++;
}
if(!s6.isEmpty()) {
n6 = Integer.parseInt(s6);
counter++;
}
if(counter>0) {
s1 = String.valueOf((n1 + n2 + n3 + n4 + n5 + n6) / counter);
average.setText(s1);
}
else {
average.setText("0");
}
counter = 0;
}
});
}
Without more details, I'll give you at least a place to start. You can instantiate TextViews programmatically and then add them to your layout.
TextView tv = new TextView(context);
parent.addView(tv);
context should be your Activity or Fragment that this text view will be apart of. The parent should be a ViewGroup in your XML layout that can have multiple children like a vertical LinearLayout. Hopefully this is enough information to guide you to better Google Searching.
EDIT
LinearLayout - Not a list layout, brain fart.
This is a sample just for reference:
The layout file:
<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:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add" />
<Button
android:id="#+id/del"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="del" />
<Button
android:id="#+id/sum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sum" />
</LinearLayout>
This is the activity:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout container;
Button add;
Button del;
Button sum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = (LinearLayout) findViewById(R.id.container);
add = (Button) findViewById(R.id.add);
del = (Button) findViewById(R.id.del);
sum = (Button) findViewById(R.id.sum);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText edit = new EditText(MainActivity.this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
edit.setLayoutParams(params);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);
container.addView(edit);
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
if (count > 0)
container.removeViewAt(count - 1);
}
});
sum.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
int sum = 0;
for (int i = 0; i < count; i++) {
EditText edit = (EditText) container.getChildAt(i);
String numStr = edit.getText().toString();
if (numStr == null || !(numStr.length() > 0)) {
sum += 0;
} else {
sum += Integer.parseInt(numStr);
}
}
Log.i("Test", "sum = " + sum + " avg = " + (sum * 1.0f / count));
}
});
}
}
Related
I'm getting four errors all with this message: cannot be resolved or is not a field
The errors are in two different .java files
StartScreen.java.text
tv = (TextView) findViewById(R.id.startscreen); (startscreen underlined in red)
Button startButton = (Button) findViewById(R.id.play_game); (play_game underlined in red)
I creaded a textview called startscreen and a button called startButton inside game.xml
PlayGame.java
tv2 = (TextView) findViewById(R.id.game_text); (game_text underlined in red)
Button startButton = (Button) findViewById(R.id.end_game); (end_game underlined in red)
I creaded a textview called game_text and a button called end_game inside game.xml
StartScreen.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class StartScreen extends Activity {
private static final int PLAY_GAME = 1010;
private TextView tv;
private int meaningOfLife = 42;
private String userName = "Douglas Adams";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.startscreen.text);
//Display initial values
tv.setText(userName + ":" + meaningOfLife);
//Set up button listener
Button startButton = (Button) findViewById(R.id.play_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startGame();
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {
meaningOfLife = data.getExtras().getInt("returnInt");
userName = data.getExtras().getString("returnStr");
//Show it has changed
tv.setText(userName + ":" + meaningOfLife);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startGame() {
Intent launchGame = new Intent(this, PlayGame.class);
//passing information to launched activity
launchGame.putExtra("meaningOfLife", meaningOfLife);
launchGame.putExtra("userName", userName);
startActivityForResult(launchGame, PLAY_GAME);
}
}
PlayGame.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PlayGame extends Activity {
private TextView tv2;
int answer;
String author;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tv2 = (TextView) findViewById(R.id.game_text);
//reading information passed to this activity
//Get the intent that started this activity
Intent i = getIntent();
//returns -1 if not initialized by calling activity
answer = i.getIntExtra("meaningOfLife", -1);
//returns [] if not initialized by calling activity
author = i.getStringExtra("userName");
tv2.setText(author + ":" + answer);
//Change values for an example of return
answer = answer - 41;
author = author + " Jr.";
//Set up button listener
Button startButton = (Button) findViewById(R.id.end_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Return information to calling activity
Intent i = getIntent();
i.putExtra("returnInt", answer);
i.putExtra("returnStr", author);
setResult(RESULT_OK, i);
finish();
}
});
}}
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="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/startscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="115dp"
android:layout_marginTop="164dp"
android:text="TextView" />
<Button
android:id="#+id/play_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/startscreen"
android:layout_below="#+id/startscreen"
android:layout_marginTop="64dp"
android:text="Button" />
</RelativeLayout>
game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/game_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/end_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Your textview id on your xml is startscreen
Instead of v = (TextView) findViewById(R.id.startscreen.text); just remove the .text part
in startscreen.java you have tv = (TextView) findViewById(R.id.startscreen.text); and in your activity_main.xml you have android:id="#+id/startscreen".
what you should do :
1-is removing the .text from tv = (TextView) findViewById(R.id.startscreen.text);
2- clean and build you project again. (if this didn't work , close and open eclipse again.
i suggest to use ctrl + space in completing you statement, that would help in reducing error and give suggestion.
Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
activity_main.xml
<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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
I am new to Android developing and I am trying to make a simple app as practice. All it consists of is you type one number into the first box, a number into the second box, press a button and the result prints into a textview. The problem is, when I press the send button Nothing is happening. Eclipse is not showing any errors, nor is LogCat. So I am officially stumped as to why when I run this I'm not getting anything out. Hopefully you guys can help.
Here is the 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="172dp"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="#+id/textView1"
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="48dp"
android:text="First Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="40dp"
android:text="Second Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignTop="#+id/textView1"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/linearLayout1"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:text="Calc" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
And here is the Java:
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void main(String[] args){
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {}
});}}
You are parsing the wrong string..
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
What you are doing now is parsing the strings "num1" and "num2" into a string and I don't think that is what you want. So it should be:
int x = Integer.parseInt(num1.getText().toString());
int y = Integer.parseInt(num2.getText().toString());
And also move the code into the onCreate() method just like #AndroidEnthusiastic suggested.
public void main(String[] args)
For Android it is a simple method,not an entry point that by the way supposed to be :
public static void main(String[] args)
I can't see that you are calling your main method in your code.
num1.getText().toString();
num2.getText().toString();
You just get the values without assigning it to any properties.
This code is totally wrong.
I suggest you to start from the beginning with official Android Training : Building Your First App.
Hye Diamond you are doing something wrong. Its ok your beginner. see you are creating main mothod. In java main method public static void main get executed first but here once activity created oncreate method will execute. So you can do it in following ways:
//inside oncreate method do like this
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int val1 = num1.getText().toString();
int val2 = num2.getText().toString();
int x =Integer.parseInt(val1);
int y =Integer.parseInt(val2);
int nas = x + y;
tv.setText(nas);
}
});
this might be help you. It's not tested. May be you have to do some changes.
Here is the complete solution
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please take a look at this link
Find this code.. hope it helps
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
String x;
String y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
sum = (Button) findViewById(R.id.button1);
sum.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
Integer nas;
x = num1.getText().toString();
y = num2.getText().toString();
nas = Integer.parseInt(x) + Integer.parseInt(y);
tv.setText(nas.toString());
}
}
}
Please try this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class add extends Activity {
Button button1;
EditText txtbox1,txtbox2;
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtbox1= (EditText) findViewById(R.id.txtbox1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.lbl1);
txtbox2= (EditText) findViewById(R.id.txtbox2);
button1.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
vis = Integer.parseInt(a)+Integer.parseInt(b);
tv.setText(vis.toString());
}
}
}
Try this,
int x =Integer.valueof(""+num1.getText().toString());
int y =Integer.valueof(""+num2.getText().toString());
int nas = x + y;
tv.setText(""+String.valueof(nas));
Please refrain from using the main function. It's not really required in an activity class and also not a general practice. #AndroidEnthusiastic has given the correct code.
Added:
Since the aforementioned answer of mine was downvoted, I'll go ahead and just tell you what you've done wrong in your code(there's a lot of code in the other answers given here).
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();//Store this in a string say a
num2.getText().toString();//Store this in a string say b
/*you're actually the passing the literal "num1" or "num2". Something which you don't want.
Instead, pass the strings a and b instead of num1 and num2 respectively*/
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*You need to put the code here. i.e. You need to take the values from the
editTexts and store them in strings and finally integers when the button is clicked.*/
}
});
Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}
How to give click-able effect for the buttons whose background is an image ? Though it functions correctly but its just looking like an image. Any help would be appreciated.
You have to create different images and put them in a selector. Take a look at this tutorial for further details:
Custom Button Backgrounds Using A Selector XML Layout
This is what I did for my dice game.
In your XML you can do:
<?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" />
<ImageButton
android:id = "#+id/dice1"
android:src = "#drawable/red_1_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginTop = "60px"
android:layout_marginLeft = "30px" />
<ImageButton
android:id = "#+id/dice2"
android:src = "#drawable/red_2_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginLeft = "250px"
android:layout_marginTop = "-130px"/>
<ImageButton
android:id = "#+id/dice3"
android:src = "#drawable/red_3_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginLeft = "135px"
android:layout_marginTop = "20px" />
In Your MainActivity.Java you can do:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.Random;
public class Z_veselinovic_yahtzeeActivity extends Activity
{
/** Called when the activity is first created. */
ImageButton button1, button2, button3, button4, button5;
Button start, reroll, hold;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
}
public void Buttons()
{
button1 = (ImageButton)findViewById(R.id.dice1);
button2 = (ImageButton)findViewById(R.id.dice2);
button3 = (ImageButton)findViewById(R.id.dice3);
button4 = (ImageButton)findViewById(R.id.dice4);
button5 = (ImageButton)findViewById(R.id.dice5);
start = (Button)findViewById(R.id.Start);
reroll = (Button)findViewById(R.id.Reroll);
hold = (Button)findViewById(R.id.Hold);
reroll.setVisibility(View.GONE);
hold.setVisibility(View.GONE);
start.setOnClickListener(new OnClickListener()
{
public void onClick(View whatever)
{
Toast.makeText(getBaseContext(), start.getText() + " Game", Toast.LENGTH_LONG).show();
Random rand1 = new Random();
Random rand2 = new Random();
Random rand3 = new Random();
Random rand4 = new Random();
Random rand5 = new Random();
int dice_num_1 = rand1.nextInt(6) + 1;
int dice_num_2 = rand2.nextInt(6) + 1;
int dice_num_3 = rand3.nextInt(6) + 1;
int dice_num_4 = rand4.nextInt(6) + 1;
int dice_num_5 = rand5.nextInt(6) + 1;
if(dice_num_1 == 1)
{
button1.setImageResource(R.drawable.red_1_dice);
}
else if(dice_num_1 == 2)
{
button1.setImageResource(R.drawable.red_2_dice);
}
else if(dice_num_1 == 3)
{
button1.setImageResource(R.drawable.red_3_dice);
}
else if(dice_num_1 == 4)
{
button1.setImageResource(R.drawable.red_4_dice);
}
else if(dice_num_1 == 5)
{
button1.setImageResource(R.drawable.red_5_dice);
}
else if(dice_num_1 == 6)
{
button1.setImageResource(R.drawable.red_6_dice);
}
I hope this helps.
This is my simplest solution especially for round button.
android:background="?android:selectableItemBackgroundBorderless"
Or you can also try this
android:background="?android:actionBarItemBackground"