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);
Related
I am new to Android programming and tried to create a small App. I have a MainClass with one EditText and one TextField. EditText is for users to type in a number and the TextField shows the value of the input when clicking on the first button. The second button is for switching to the other class (MainClass2). Now i want to show the input number from EditText (that I defined as "number") in the next class MainClass2 in an empty TextField. I implemented an OnClickListener for the two different buttons mentioned in the MainClass (first screen). Since I only defined the input variable "number" when clicking the first button (cause "number" is then shown in the TextField as mentioned because it is only created via EditText when clicking the first button), "number" is not defined in the code of clicking the second button. Therefore I cant hand it over to the MainClass2 via Intent. Do you have any solutions for this? Thank you in advance. These are the codes for my Classes:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
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 button2 = findViewById(R.id.button2);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(this);
}
public void onClick(View v) {
// default method for handling onClick Events..
switch (v.getId()) {
case R.id.button:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
TextView textView = findViewById(R.id.textView);
textView.setText(String.valueOf(number));
Random randomizer = new Random();
int name = randomizer.nextInt(number+1);
TextView textView2 = findViewById(R.id.textView2);
if (name == 1 ) {
textView2.setText("Player 1");
}
if (name == 2 ) {
textView2.setText("Player 2");
}
break;
case R.id.button2:
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number); //here is the error cause number is not
defined, although it is..
startActivity(intent);
break;
default:
break;
}
}
}
And this is the code for MainClass2:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
String number = intent.getStringExtra("number");
textView3.setText(number);
}
}
In case R.id.button2: you have not set the value of number. So it will give number undefined error. To solve this issue either you have to initialize number globally or get the value of number in case R.id.button2: also. Like
case R.id.button2:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
Intent intent =
new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number);
startActivity(intent);
break;
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);
}
});
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()?
I'm trying to get an add button to add another button to the layout, based on the edittext to the left of the button. The point is for a person to list the rooms in their house, and then when they type in each room, a new button is generated so they can click the room, and then start working on the next page.
I had an xml layout all done, and then I realized I'm "programmatically" adding buttons, so I redid the layout programmatically, and then in the switch/case (that's how I do onclicks) for the add button I tried to add a button to the view, but it's getting very tricky. I'd like to have a scrollview below the edittext and add buttons, and as they add all the rooms to their house it eventually is populated with a scrollable list of buttons for their entire home. Is there a way to add buttons programmatically to an xml'd layout. I was thinking you can but everything I'm trying just isn't working.
Thanks for your help everybody, any recommendations you have would be greatly appreciated.
First Edit (in response to Tanuj's solution)
My XML file (not sure if we're going to use this or just use the java):
<?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/tvAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvAddARoom" />
<EditText
android:id="#+id/etAddARoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/etAddARoom" />
<Button
android:id="#+id/btnAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAdd" />
<TextView
android:id="#+id/tvSelectARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvSelectARoom" />
<TextView
android:id="#+id/tvNoRooms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvNoRooms" />
<Button
android:id="#+id/btnViewAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnViewAll" />
</LinearLayout>
And the Java. This isn't at all correct, as in the java I'm creating the whole layout instead of using the layout above. Just not sure if I can bridge the two.
package com.bluej.movingbuddy;
import android.app.Activity;
import android.os.Bundle;
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;
//import android.widget.ScrollView;
import android.widget.TextView;
public class EstimatorByRoom extends Activity implements OnClickListener {
String roomName;
EditText etAddARoom;
LinearLayout layout;
LinearLayout.LayoutParams layoutParam;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.estimatorbyroom);
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
//create a layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//create a text view
TextView tvAddARoom = new TextView(this);
tvAddARoom.setText("Add a Room");
tvAddARoom.setLayoutParams(params);
//create an edittext
EditText etAddARoom = new EditText(this);
etAddARoom.setHint("Living Room, Dining Room, etc.");
etAddARoom.setLayoutParams(params);
//create a button
Button btnAddARoom = new Button(this);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
//adds the textview
layout.addView(tvAddARoom);
//add the edittext
layout.addView(etAddARoom);
//add the button
layout.addView(btnAddARoom);
//create the layout param for the layout
LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
this.addContentView(layout, layoutParam);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//this part isn't working!
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
layout.addView(createdButton);
this.addContentView(layout, layoutParam);
//if no rooms make tvnorooms disappear
break;
}
}
}
Try this :
//the layout on which you are working
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);
Try this code:
LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_layout);
l_layout.setOrientation(LinearLayout.VERTICAL); // or HORIZONTAL
Button btn1 = new Button(this);
btn1.setText("Button_text");
l_layout.addView(btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// put code on click operation
}
});
that is a way to create button dynamically and add in Layout.
remember that when you create button programmatically you just use this not Class_name.this
public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {
final int TOP_ID = 3;
final int BOTTOM_ID = 4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create two layouts to hold buttons
LinearLayout top = new LinearLayout(this);
top.setId(TOP_ID);
LinearLayout bottom = new LinearLayout(this);
bottom.setId(BOTTOM_ID);
// create buttons in a loop
for (int i = 0; i < 2; i++) {
Button button = new Button(this);
button.setText("Button " + i);
// R.id won't be generated for us, so we need to create one
button.setId(i);
// add our event handler (less memory than an anonymous inner class)
button.setOnClickListener(this);
// add generated button to view
if (i == 0) {
top.addView(button);
}
else {
bottom.addView(button);
}
}
// add generated layouts to root layout view
LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
root.addView(top);
root.addView(bottom);
}
#Override
public void onClick(View v) {
// show a message with the button's ID
Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
toast.show();
// get the parent layout and remove the clicked button
LinearLayout parentLayout = (LinearLayout)v.getParent();
parentLayout.removeView(v);
}
}
Each button needs to have an onclicklistener to tell it what to do. this can be added to your java code under where you state your button.
Button createdButton = new Button(this);
createdButton.setOnClickListener(new OnClickListener()
{
code you want implemented
}
I would add an id to your LinearLayout in xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
And then change your onClick to this:
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//Find you parent layout which we'll be adding your button to:
LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.addView(createdButton);
//if no rooms make tvnorooms disappear
break;
}
}
I have a image button and i want that image button when pressed it changes the text in a textbox and it changes a image to a different image how do i do this?
You need an OnClickListener: http://developer.android.com/reference/android/view/View.OnClickListener.html
When clicked your text can be changed with (something like) text.setText("new text");
I'll find a link in a minute which will help more.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class TestesetetActivity extends Activity {
/** Called when the activity is first created. */
TextView textview = null;
ImageButton buttonResume = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonResume = (ImageButton) findViewById(R.id.imageButton1);
textview = (TextView) findViewById(R.id.textView1);
buttonResume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textview.setText("test");
buttonResume.setImageResource(R.drawable.push_pin);
}
});
}
}
In the xml file, you can give the image an onClick attribute, which calls a method in the java class, which calls the xml resource, and passes it the id of the ImageView.
In that java method, you can use
((ImageView) view).setImageResource(int id)
or
setImageDrawable(Drawable d)
to change the image.
Likewise, you can identify the TextView you wish to change using, for example,
TextView tv = (TextView) findViewById( id )
with id being the id of the TextView you wish to find.
You can then use
tv.setText(String s)
to set the text in this view.
In your OnClickListener, you could use
button.setBackgroundResource(YOUR_BUTTON_ID);
or
button.setImageResource(YOUR_BUTTON_ID);