This code isn't calling the next activity. I don't understand why, but this onClick method isn't starting the next activity, though the same code in other activities does. Tested calling other activities and it didn't work even. The button is created, but when I tap it, nothing happens.
Edit: Folks, when we make a question about code, we want to know what is wrong, why is wrong, how to fix and why and this fixing works. We want to understand both the problem and the solution, and just drop a sample of code alone as an answer doesn't quite help some people. I thank you all for spending time with my question and for helping me solve this issue, but keep this words in mind when you are answering someone's question.
package com.example.conjuradortormenta;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class ListadePersonagens extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listade_personagens);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Using shared preferences, we get information about the characters
SharedPreferences informacoesdepersonagem = getSharedPreferences("com.example.conjuradortormenta_informaçoes_de_personagem", MODE_PRIVATE);
int num = informacoesdepersonagem.getInt("numero_de_personagens", 0);
String nome, resumo;
Button botao[]= new Button[num+1];
if(num!=0)
{
for(int i=1; i<=num; i++)// cria os botões de cada personagem
{
nome = informaçõesdepersonagem.getString("nome_personagem"+(i+1), "Nenhum");
resumo = informaçõesdepersonagem.getString("raça_personagem"+(i+1), "Nenhum")+ " " + informaçõesdepersonagem.getString("classe_personagem"+(i+1), "Nenhum") + " " + Integer.toString(informaçõesdepersonagem.getInt("nivel_personagem"+(i+1), 0));
botao[i]=new Button(this);
botao[i].setText(nome+" "+resumo);
botao[i].setId(i);
botao[i].setOnClickListener(this);
layout.addView(botao[i]);
}
}
botao[0]=new Button(this);
botao[0].setText("Criar Novo");
botao[0].setId(1);
botao[0].setOnClickListener(this);
layout.addView(botao[0]);
}
#Override
public void onClick(View view)
{
Intent nova = new Intent (this, CriadordePersonagem.class);
startActivity(nova);
}
}
You seem to add a bunch of buttons to your LinearLayout, but you don't actually add layout to your view hierarchy. Can you try calling setContentView(layout) and clicking on the buttons then?
I think you can use this example :-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
startActivity(new Intent(this, Doctor.class));
break;
}
}
}
Would be useful to see your XML layout, but my first guess is that you didn't add the layout anywhere.
Your layout seems to be R.layout.activity_listade_personagens so if you want to edit it, you should get it instead of creating a new one:
setContentView(R.layout.activity_listade_personagens);
LinearLayout layout = findViewById(R.layout.activity_listade_personagens);
layout.setOrientation(LinearLayout.VERTICAL);
// Rest of your code
In onClick method, you did not get Id of which view be clicked. So android cannot know onClick for what view. You should do that:
#Override
public void onClick(View view){
switch (view.getId()){
case R.id.button:
Intent nova = new Intent (this, CriadordePersonagem.class);
startActivity(nova);
break;
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OneActivity.this, TwoActivity.class);
startActivity(intent);
}
});
Related
This question already has answers here:
Multiple Buttons' OnClickListener() android
(11 answers)
Closed 7 years ago.
When you have many buttons in a view and all the button have listener. Your main activity gets dirty.
Anyone know how to organize listeners ?
Currently I used this way and implement onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3){
//button3 action
}
}
You can implement onclicklistner for multiple buttons using swith case
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.firstButton:
// do your code
break;
case R.id.secButton:
// do your code
break;
case R.id.thirdButton:
// do your code
break;
......
default:
break;
}
}
Ya...It s the best way to use multiple onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.spotifyBtn:
intent = new Intent(this, SimpleSingleExample.class);
break;
case R.id.superDuoBtn:
intent = new Intent(this, CustomExample.class);
break;
case R.id.libraryBtn:
intent = new Intent(this, SequenceExample.class);
break;
case R.id.buildItBiggerBtn:
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
break;
}
if(intent!=null){
startActivity(intent);
}
}
If you want better way than you have to use Android Annotations, its simple and useful, you can find here
Add those View object references to some type of list, iterate through it usin a for-each loop, then call the setOnClickListener on each element which will reduce those lines to just 2 lines for you.
ArrayList <View> list = new ArrayList <>(spotify,superDuoBtn,libraryBtn, buildBiggerBtn, capstoneBtn);
for (View view : list) {
view.setOnClickListener(this);
}
The most obvious example of alternative approaches to solving a single problem seems to be the various ways you can handle button clicks. As far as I know, there are four different ways to add listeners for handling button clicks. If you know of other ways, please post a comment and share them with us.
Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Inner Class (btn1)" android:id="#+id/Button01"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<Button android:text="Anonymous Inner Class (btn2)"
android:id="#+id/Button02" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Implementing an Interface (btn3)"
android:id="#+id/Button03" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Calling From XML Layout (btn4)"
android:id="#+id/Button04" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btn4Listener">
</Button>
</LinearLayout>
in MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//method 1 - uses an inner class named btn1Listener...
Button btn1 = (Button)findViewById(R.id.Button01);
btn1.setOnClickListener(btn1Listener);
//method 2 - use an anonymous inner class as a listener...
Button btn2 = (Button)findViewById(R.id.Button02);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn2 - uses an anonymouse inner class");
}
});
//method 3 - note that this class implements
//the View.OnClickListener interface
//which means that we must implement the onClick()
//method (which you'll find below)..
Button btn3 = (Button)findViewById(R.id.Button03);
btn3.setOnClickListener(this);
//method 4 - look at the method btn4Listener() below
}
//here's the inner class used as a listener for btn1...
private View.OnClickListener btn1Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn1 - uses an inner class named btn1Listener");
}
};
//here's a method that you must have when your activity implements the
//View.OnClickListener interface...
#Override
public void onClick(View v) {
showToastMessage("you clicked on a btn3, which uses this Activity as the listener");
}
//here's the handler for btn4 (declared in the xml layout file)...
//note: this method only works with android 2.1 (api level 7), it must be public and
//must take a single parameter which is a View
public void btn4Listener(View v) {
showToastMessage("You clicked btn4 - listener was set up in the XML layout");
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
I know that title is fancy but this is going on in my android app.
I am storing the names of websites which user wants to open in an arraylist of strings. Then an array of buttons is made whose size depends on the size of arraylist.
Then I set the text of the buttons using the arraylist. This works perfectly and all the buttons are assigned correct text.
Then I set the on click listeners of each button and create an implicit intent to open the web site.
Problem that is occuring is that despite the fact the text of the buttons are set perfectly , There is some problem with the listener because no matter which button i press, always the site of last button is opened and hence last button dictatorship.
Here is my code.
package com.example.hp.myproject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created #CreativeLabsworks
*/
public class Act3 extends Activity
{
LinearLayout ll1; Button[] bt_arr; String s;
LinearLayout.LayoutParams params1;
ArrayList<String> sites;TextView t1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent=getIntent();
sites= intent.getStringArrayListExtra("arraylist");
/*Creating a linear layout to hold editTexts*/
ll1=new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
/*set the width and height of the linear layout*/
params1=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
setContentView(ll1, params1);
/*Initializing the button array*/
bt_arr = new Button[sites.size()];
/*Initialize each button*/
for(int i=0;i<bt_arr.length;++i)
{
bt_arr[i] = new Button(this);
ll1.addView(bt_arr[i]);
}
setText();
attach_listeners();
}
public void attach_listeners()
{
/*this function attaches listeners with all buttons in the button array*/
for(int i=0;i<bt_arr.length;++i)
{
s=sites.get(i);
bt_arr[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
}
});
}
}
public void setText()
{
/*This function sets the text of the various buttons*/
int j;
for(int i=0;i<bt_arr.length;++i)
{
j=sites.get(i).indexOf(".com");
bt_arr[i].setText(sites.get(i).substring(4,j));
}
}
}
The problem that you have is that
s=sites.get(i);
S is being set by the last element.
Whenever a button is clicked it is taking the S from the last element since S is outside the onClickListener instance that you have.
I would suggest to save the url in the Button tag and then use it When the button is clicked.
for (int i = 0; i < bt_arr.length; ++i) {
s = sites.get(i);
bt_arr[i].setTag(s);
bt_arr[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String website = (String)v.getTag();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://" + website));
startActivity(i);
}
});
}
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
Maybe you do not write i.setclass()?
So I'm new to android development and I'm having a bit a of a trouble.
I'm developing an an app which is going to have a similar background every time but imports a new image every time the user touches the screen.
HOWEVER my problem is that I'm having an issue right now in which I'm trying to load a new activity when a user click a button, 1) I followed one tutorial which had me use XML to add the button and program MAIN_activity to to switch to second_Activity using setcontent(R.layout.main_Activity) and works fine.
2) I also started another tutorial which had me use setContent(layout1) where layout one is in fact a LinearLayout which you addView(stuff) such as a button and program it to switch the second activity, but I'm failing terribly.
long story short, using this line setcontent(R.layout.main_Activity) overrides the setContent(layout1) info and I cant combine them. In addition I dont know how to make a button and click to switch activity except using the first method, I'm open to suggestions.
package self.name.firstandroidprogram;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
setContentView(R.layout.activity_main);// Works
// setContentView(layout1) failes when i run
}
I am not sure, but try it
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
// Do it before adding views in it.
setContentView(layout1);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
// setContentView(R.layout.activity_main);// Works
}
You can set LinearLayout as your main layout. When user clicks the switch button, you need to set background of the LinearLayout
activity_main.xml :
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/main"
android:background="#drawable/default"
>
<!-- put your Button here switch button -->
</LinearLayout>
MainActivity.java :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchButton = (Button)findViewById(R.id.button1);
LinearLayout lv1 = (LinearLayout) findViewById(R.id.main);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// we have reference of LinearLayout as lv1
// we will change background of lv1 here when user clicks
lv1.setBackgroundResource(<your_new_background_image_id>);
}
});
<your_new_background_image_id> can be fetched from /res/drawable/ folder. You store 10-20 images of small size in drawable and rename them with similar name i.e. image1, image2 etc
When setting them as background, you can code like :
int[] imageArray = {R.drawable.image1, R.drawable.image2,...}
lv1.setBackgroundResource(imageArray[(i++)%10]);
If you are creating view programatically you have to set each view LayourParameters using view.setLayoutParams()
Try this
layout1 = new LinearLayout(this);
EditText number1Text = new EditText(this);
EditText number2Text = new EditText(this);
Button calcButton = new Button(this);
calcButton.setText("X");
//impt : width=MATCH_PARENT and height=MATCH_PARENT
layout1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
layout1.setOrientation(LinearLayout.VERTICAL); //setting LL orientation
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
setContentView(layout1);
I am testing the longclick and the short click features for a simple standalone project. What I am planning to do is, when I click on a button/header it will call a fragment , but when I long click viz., even without releasing my finger , I want the popup to show. My current implementation shows the popup no matter I do a long click or a short click. I would like toshow popup only upon long click and not upon short click. Also, through the popup select menu,I want to trigger a related fragment to the options selected.Is there a way to do this?Can you modify my existing code to reflect that?
Thanks!
Here's my code:
Mainactivity.java:
package com.example.longclick;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnList = (Button)this.findViewById(R.id.btnListSample);
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = {"Personal Lists", "Shared Lists"};
AlertDialog.Builder listBuilder = new AlertDialog.Builder(MainActivity.this);
listBuilder.setTitle("Manage Categories");
listBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
}
});
}
}
and associated xml:
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Lists Header"
android:id="#+id/btnListSample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</Button>
</LinearLayout>
Well you should implement your own code but here are the basics
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vi) {
}
});
btnList.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
Try changing your button a text view or something else. Then for that object, add two listeners:
onLongClickListener
and
onClickListner
you could try adding the onLongClickListener to the button object but I'm not sure if that is possible or not.
you should add OnLongClickListener to the button:
btnList.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public void onLongClick(View v) {
//what you want to do
}
});
You can call start an activity from the dialog, and make fragment transaction too, but i don't understand what exactly you want to do.
I used to have some experience with developing for android but I started up again after 6 months and forgot most of it. I am now using a macbook to do my developing on and had to set up Eclipse, the Android SDK and AVD all over again and I'm worried I messed something up.
When I start a new project with the default activity that displays "Hello World" on my screen the app runs fine. I then tried to put in two buttons that cause the text in a new TextView to change. But whenever I include the textView part I get a runtime error. When I comment it out, the app runs but obviously nothing happens. Based upon the tutorials I've been reading, this is the appropriate place and way to declare/create the textView but I can't figure out what's wrong. Any suggestions?
[Edit] I was messing around and found that I can make the mytext a field instead of a TextView and that worked. So in my onCreate(), I put
mytext = (TextField)findViewById(R.id.TextView1);
but that doesn't seem the right way to do things.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class IntroActivity extends Activity {
TextView myText = (TextView)findViewById(R.id.textView1);
//i've tried this with final added on to it as well (recommended by eclipse)
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonClickListener();
}
private void setButtonClickListener() {
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText.setText("Hello");
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// myText.setText("Goodbye");
}
});
}
}
This:
TextView myText = (TextView)findViewById(R.id.textView1);
should be separated. The declaration should be at the same place:
private TextView myText;
But the assignment should come only after setContentView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.textView1);
This is done since before setContentView, Dalvik doesn't know from which layout to take the view that matchs the id R.id.textView1