I have a button inside a view that checks some constraints, and then starts another activity, however the startActivity() call does not do anything, the new activity's onCreate() never gets called, and the code then continues past it. I have checked using logging and breakpoints, and the conditions are being met and startActivity() is being called. Both activities are defined in the application manifest.
From the source activity's onCreate():
int[] winning_player;
int next_player;
int[] scores;
[...]
final Button end_turn_button = (Button) findViewById(R.id.end_turn);
end_turn_button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (winning_player[0] == next_player) {
Intent intent = new Intent(getApplicationContext(), FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
});
FinalScreenActivity.java
public class FinalScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
Intent intent = getIntent();
final int[] scores = intent.getIntArrayExtra("SCORES");
// put the scoreboard in ascending order
Arrays.sort(scores);
// find the scoreboard in the view
TableLayout scoreboard = (TableLayout) findViewById(R.id.scoreboard);
// get the string resources to be formatted
Resources res = getResources();
String player_name_format = res.getString(R.string.player);
// Set the scoreboard in the view
Log.d("brains.PlayActivity", "onCreate: Creating scoreboard");
// for each player entry in the scoreboard
for (int i = 0; i < scores.length; i++) {
Log.d("brains.PlayActivity", "onCreate: adding scoreboard entry "+String.valueOf(i));
// create 2 TextViews
TextView player_name = new TextView(FinalScreenActivity.this);
TextView player_score = new TextView(FinalScreenActivity.this);
// Set the size of the TextViews
player_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// set the first one to the player's name string resource
player_name.setText(String.format(player_name_format, i + 1));
// set the second one to the player's score resource, which takes the score twice (once for the number itself, and once to work out which plural is needed)
player_score.setText(res.getQuantityString(R.plurals.brains, scores[i], scores[i]));
// Create a TableRow to put the score into
TableRow scoreboard_entry = new TableRow(FinalScreenActivity.this);
// Set the size of the TableRow
scoreboard_entry.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Add the TextViews to the TableRow
scoreboard_entry.addView(player_name);
scoreboard_entry.addView(player_score);
// Add the TableRow to the TableLayout
scoreboard.addView(scoreboard_entry);
}
// Get the title text
TextView title_text = (TextView) findViewById(R.id.title_text);
title_text.setText(res.getQuantityString(R.plurals.win_brains, scores[scores.length - 1], scores.length - 1, scores[scores.length - 1]));
// set the play again button
Button play_again_button = (Button) findViewById(R.id.play_again_button);
play_again_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SelectPlayersActivity.class);
startActivity(intent);
}
});
}
}
and activity_final_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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="uk.co.bluesapphiremedia.android.zombiedice.FinalScreenActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/scoreboard"
android:layout_below="#+id/title_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_again"
android:id="#+id/play_again_button"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
end_turn_button.setOnClickListener(this);
//override onClick() method in activity implement interface View.OnClickListner
public void onClick(View v) {
if(v.getId() == R.id.end_turn){
if (winning_player[0] == next_player) {
Intent intent = new Intent(this,FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
}
Related
In my project I have some EDITTEXT being generated at runtime , the number of EDITTEXT is variable.
Must recover typed text and store in different variables , and then create a JSON object with it.
Here is the method I use to create the EditText :
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if(tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
}
else if(tpRender.equals("DATE")) {
e.setHint("DATE");
}
else if(tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
return(e);
}
How do I get the text entered separately?
As your EditTexts are created at runtime and you need to get the value from all of them to create your json, you could use a List and store your individual EditTexts there. Something like:
In the xml file:
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:id="#+id/layout">
</LinearLayout>
In your activity,
List<EditText> allEditTexts; // The List to hold all EditTexts
LinearLayout layout; // The anchor layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layout);
allEditTexts = new ArrayList<EditText>();
// I am running it three times, you can run as many times as you want
for (int i = 0; i < 3; i++) {
EditText editText = (EditText) editText("ANY LABEL", "NUMBER");
layout.addView(editText);
allEditTexts.add(editText);
}
// Now I am adding a button that will read the values from the List when clicked
Button button = new Button(getApplicationContext());
button.setText("Click");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Read the input here for all EditTexts. Then you can store it in some Array or process it differently. In my code I have just logged them.
for (EditText editText : allEditTexts) {
Log.d("TEXTINPUT", editText.getText().toString());
}
}
});
layout.addView(button);
}
// This is the code that you have, almost untouched.
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if (tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
} else if (tpRender.equals("DATE")) {
e.setHint("DATE");
} else if (tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
allEditTexts.add(e);
return (e);
}
Hope this helps you!
I have a LinearLayout that is dynamically declared through the Run_Time, though i don't have a fixed names or tags to define that Layout, though i tried to assign a tag to wach Layout depends on some variable and retrieve it by that variable later, like that :
layout.setTag(index , "something"); // "index" is a variable it's value obtained through the run_time
but i got that error :
ERROR/AndroidRuntime(643): Caused by: java.lang.IllegalArgumentException: The key must be an application-specific resource id.
and after search i found that the problem is that i must assign a fixed resource to that tag but then i won't be able to differentiate between the different layout , so is there's a way to reach my approach?
The reason you're not able to use setTag(int, Object) is because android require a pre-compiled unique id in the 'int' argument.
one way is:
declare your tag in String file like follow:
<string name="FirstTag">1</string>
<string name="SecondTag">2</string>
and for setting that use:
layout.setTag(R.string.FirstTag, "something");
and for getting value:
layout.getTag(R.string.FirstTag).toString();
another way is create a new file called values/tags.xml and write:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item name="FirstTag" type="id">1</item>
</resources>
OR you can use R.id.* as Tag Id too, i think you can handle your problem with that
Check this out :
(Use Of Tag)
Java Code:
public class DynamicTetView extends Activity
{
RelativeLayout rl1;
Button b1;
TextView txt,txt3;
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tet_view);
rl1 = (RelativeLayout)findViewById(R.id.rl1);
b1 = (Button)findViewById(R.id.button1);
RelativeLayout.LayoutParams param2 = new RelativeLayout.
LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
param2.setMargins(5, 0, 0, 5);
txt3 = new TextView(this);
txt3.setId(500);
Log.d("Id of txt3........", ""+txt3.getId());
txt3.setText("Hii");
rl1.addView(txt3, param2);
for(i=0;i<10;i++)
{
RelativeLayout.LayoutParams param = new RelativeLayout.
LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
param.setMargins(5, 0, 0, 5);
txt = new TextView(this);
txt.setId(i+1);
txt.setTag(i+1);
Log.d("Id........", ""+txt.getId());
map.put("hi"+txt.getId(), i);
if(txt.getId()!=1)
{
param.addRule(RelativeLayout.BELOW,(txt.getId()-1));
}
else
{
param.addRule(RelativeLayout.BELOW,txt3.getId());
}
txt.setText("Text"+(i+1));
rl1.addView(txt,param);
txt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String tag = v.getTag().toString();
Toast.makeText(getBaseContext(),"You clicked "+tag, Toast.LENGTH_LONG).show();
}
});
}
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
rl1.removeAllViews();
}
});
}
}
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=".DynamicTetView" >
<RelativeLayout
android:id="#+id/rl1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:text="Clear" />
</RelativeLayout>
</RelativeLayout>
I am trying to create an android app. I have two buttons next and back in my android app. I want when i click on next button its open same activity with different background. Next time i again click next new background image. And on press on back button its show previous image. And if no previous image its shows menu on press. Similarly if background with last image its hide next button. I have no idea how to do this.
I have tried this:
#Override
public void onCreate(Bundle savedInstanceState)
{
onCreate(savedInstanceState);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.back)
{
startActivty(new Intent(this,));
}
else if(v.getId()==R.id.next)
{
startActivity(newIntent(this,));
}
}
Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back">
<Button
android:id="#+id/back"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="25dp"
android:background="#drawable/ques"
android:text="Back" />
<Button
android:id="#+id/next"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/back2"
android:layout_alignBottom="#+id/back2"
android:layout_alignParentRight="true"
android:background="#drawable/ques"
android:text="Next" />
</RelativeLayout>
In layout as you can see i am using image back for background. I want when i click next new background image then next and so on.
But i dont know how to start same activity with differene backgroud.
Don't start new Activity just change the background:
Keep an array of background resources in your activity like:
int[] backgroundResId;
and one int variable to store current background index:
int currentIndex=0;
now inside your onCreate initialize this array with resource id's of all the backgrounds drawables:
backgroundResId=new int[]{R.drawable.a,R.drawable.b,R.drawable.c};
changeBackground()
create function changeBackground in activity:
private void changeBackground(){
findViewById(R.id.root_layout).setBackgroundResource(backgroundResId[currentIndex]);
}
Now onClick of next button increase currentIndex:
currentIndex++;
if(current<=backgroundResId.length){
changeBackground();
}else{
// setVisibility of next button to invisible
}
onBackButton Click
currentIndex--;
if(current>=0){
changeBackground();
//// setVisibility of next button to visible
}else{
//show menu
}
Make an images array and post your data to the next activity:
Intent intent = getIntent();
intent.putExtra("background", imageIdInTheImageArray);
startActivity(intent);
//finish();
and in your onCreate function :
Bundle b = getIntent().getExtras();
if (b != null) {
int background = b.getInt("background");
//set your background
}
You can add an ImageView in your xml file.
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
you can change background using this
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setBackgroundResource(resId);
Try this..
Global:
int[] backgrounds = new int[]{ images in drawable as int array };
int count = 0;
Button back,next;
RelativeLayout img_backn_lay;
JAVA:
setContentView(R.layout.activity_main);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
img_backn_lay = (RelativeLayout) findViewById(R.id.main_lay);
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
ClickListener:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.next)
{
if(backgrounds.length != count){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
else if(v.getId()==R.id.back)
{
if(count != 0){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count -= 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_lay"
android:layout_width="match_parent"
android:layout_height="match_parent" >
Hi i'm having an issue with placing buttons at the bottom of the screen i have laid it out and in the graphical layout in eclipse it looks exactly how i want it but when i run it on the device the buttons both go to the very bottom of the screening the same position. so only one button is visible. does anyone know why this is or do you know how to place thing s at the bottom with a bit of padding?
heres what i have tried
<?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:background="#drawable/ic_background_credits"
android:orientation="vertical" >
<Button
android:id="#+id/fm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:background="#drawable/fmbtn" />
<Button
android:id="#+id/ph"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/fm"
android:layout_alignLeft="#+id/fm"
android:background="#drawable/visitphbtn" />
</RelativeLayout>
heres my code where i inflate this view
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Check Preferences which sets UI
setContentView(R.layout.singlenews);
findViewById(R.id.progress).setVisibility(View.GONE);
loadData();
Button backbtn = (Button) findViewById(R.id.backbtn);
//Listening to button event
backbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent previousScreen = new Intent(getApplicationContext(), InfoActivity.class);
startActivity(previousScreen);
}
});
}
public void loadData(){
name = getIntent().getStringExtra("name");
Log.v("lc", "infoname=" + name);
if (name.equals(name1")) {
NewsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.infodetail,
null);
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText("About name1");
TextView mainText = (TextView) NewsView.findViewById(R.id.maintext);
mainText.setText("name1");
ImageView NewsImage = (ImageView)NewsView.findViewById(R.id.imageView2);
NewsImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_logo_evostik));
}
if (name.equals("name2")) {
NewsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.infodetail,
null);
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText("About name2");
TextView mainText = (TextView) NewsView.findViewById(R.id.maintext);
mainText.setText("name2");
ImageView NewsImage = (ImageView)NewsView.findViewById(R.id.imageView2);
NewsImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_logo_pitchero));
}
if (name.equals("name3")) {
NewsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.creditsdetail,
null);
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText("name3");
Button phbtn=(Button)NewsView.findViewById(R.id.ph);
phbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Uri uri = Uri.parse("http://www.pitchero.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
Button fmbtn=(Button)NewsView.findViewById(R.id.fm);
fmbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Uri uri = Uri.parse("http://www.fantasticmedia.co.uk/mobile/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
ListView list = getListView();
list.setVerticalFadingEdgeEnabled(false);
Log.v("BGThread", "Filled results");
adapter = new MergeAdapter();
adapter.addView(NewsView);
setListAdapter(adapter);
}
}
I think you have some attributes mixed up.
In your second button don't add the '+' operator to id because it's making a new one. Just remove it and leave the '#'.
Remember '+' adds to id and '#' references it.
Well relative layout is relative to the other items inside the RelativeLayout container which is a ViewGroup. So for example you could specify android:layout_leftOf="#+id/fm" in the description of pm. If you want padding you might also expiriment with margin and padding like inside the buttons.
android:layout_marginBottom="20dip"
android:layout_leftOf="#+id/fm"
android:paddingBottom="10dip"
I actually try your Layout in my project and the two buttons are correctly placed.
Are you sure you didn't make any other actions in your code ?
In my soundboard app I have 80 buttons that have a on click listener and a on long click listener.
My buttons are declared in xml as:
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content" >
<Button
android:id="#+id/sound0"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound0" >
</Button>
<Button
android:id="#+id/sound1"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound1" >
</Button>
<Button
android:id="#+id/sound2"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound2" >
</Button>
</TableRow>
And the listeners are set as:
Button SoundButton0 = (Button) findViewById(R.id.sound0);
SoundButton0.getBackground().setAlpha(150);
SoundButton0.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Play", name, 0);
playSound(R.raw.sound0);
}
});
SoundButton0.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Saved", name, 0);
ring(soundArray[0], name);
return false;
}
});
Is there a way I can do all of this programmatically in a for loop so that the only thing changed for each button is SoundButtonx where x is increased by one for each button.
Yes there is a clear solution:
Button[] buttons;
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "sound" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setOnClickListener(this);
}
Note: Declare XML layout with buttons having id like sound1, sound2, sound3, sound4....and so on.
A more clear-cut example is here for the same problem => Android – findViewById() in a loop
Yes there is. Inside your for loop, you first declare a Button, and pass its constructor a context. Then you set each button's layout params. Add each button to the parent view (use the addView method on the parent view). Finally, use the setContentView method of the activity and pass the parent as a param.
yes take a look at this
for(int x = 0;x<80;x++)
{
Button btn = new Button(this);
btn.setlayoutParams(new LayoutParams(LayoutParams.wrap_content,LayoutParams.wrap_conmtent);
btn.setId(100 + x);
btn.setOnClickListener(this);
btn.setOnlongClickListener(this);
this.addView(btn);
}
//this will create 80 buttons and setlisteners on them
//in your overrides of onclick and onLongClick identiffy them as
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
if(id == 100 + 1 )
{
//your code
}