Setting views as global variables android - android

I have three functions in my Main class, onCreate,onClick and click, I have two options, declare TextViews and some other views at the beginning of the project as global variables, which means they will stay in the entire app lifetime, or get them separately in each function(will cause the computer to work a bit more but the variables will not stay in memory the whole time). To describe the question further:
OPTION 1:
public static final int L = 6;
TextView[] textViews = new TextView[L];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
int[] digits = {rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)};
for (int i = 0; i < L; i++) {
textViews[i] = (TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(i), "id", getPackageName()));
textViews[i].setOnClickListener(this);
textViews[i].setText(String.valueOf(digits[i]));
}
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(0);
break;
case R.id.num1:
click(1);
break;
case R.id.num2:
click(2);
break;
case R.id.num3:
click(3);
break;
case R.id.num4:
click(4);
break;
case R.id.num5:
click(5);
break;
}
}
public void click(int clicked) {
textViews[clicked].setText("Clicked");
}
OPTION 2: (Note to shorten your time - the change is in the last function).
public static final int L = 6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
int[] digits = {rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)};
for (int i = 0; i < L; i++) {
textViews[i] = (TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(i), "id", getPackageName()));
textViews[i].setOnClickListener(this);
textViews[i].setText(String.valueOf(digits[i]));
}
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(0);
break;
case R.id.num1:
click(1);
break;
case R.id.num2:
click(2);
break;
case R.id.num3:
click(3);
break;
case R.id.num4:
click(4);
break;
case R.id.num5:
click(5);
break;
}
}
public void click(int clicked) {
((TextView) findViewById(getResources().getIdentifier("num" + String.valueOf(clicked),"id",getPackageName())).setText("Clicked");
}
Take into consideration I have more than a TextView array, and in some function I have to get 5 views again, will it be better to declare them as global variables? I read somewhere most of the time using global variables is not good and it is against the whole idea of functions, but it seems more simple here.. Sorry about my English and thank you all.

First off, you do not need to worry about performance issues if the textViews object is declared globally. It is minuscule.
Now in your code,if the only reason to declare textViews array object is to reference it in click() method, then there is no need of declaring it globally.
Instead, you can pass the view object provided by the overridden onClick() method to your click() method.
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.num0:
click(view);
break;
case R.id.num1:
click(view);
break;
case R.id.num2:
click(view);
break;
case R.id.num3:
click(view);
break;
case R.id.num4:
click(view);
break;
case R.id.num5:
click(view);
break;
}
}
public void click(View viewClicked) {
((TextView))viewClicked.setText("Clicked")
}

Related

How to change several texts on button click in android studio

HELP ME PLEASE! I want to create 2 buttons ("Next" and "Previous") that will change the text in TextView. I made a switch and "systemcounter" to change the cases, which then will set another text in TextView. When I test my program in this window buttons do not change the pages. I think this is because the system cannot see the "systemcounter"
private Button next_button;
private Button previous_button;
private TextView Text_set1;
int systemcounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learningpage);
next_button = (Button) findViewById(R.id.next_button);
previous_button = (Button) findViewById(R.id.previous_button);
Text_set1 = (TextView) findViewById(R.id.Text_set);
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter + 1;
}
});
previous_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter - 1;
}
});
switch (systemcounter) {
case (0):
Text_set1.setText("Thermodynamics is the branch of physics that deals with the relationships between heat and other forms of energy.");
previous_button.setVisibility(View.INVISIBLE);
break;
case (1):
Text_set1.setText("Hi there");
previous_button.setVisibility(View.VISIBLE);
break;
case (2):
Text_set1.setText("How are you");
previous_button.setVisibility(View.VISIBLE);
break;
case (3):
Text_set1.setText("How old are you?");
break;
default:
Text_set1.setText("OPS");
break;
}```
you have switch statement in oncreate method and so it executes it only once, make a seperate method like
setEditText(int systemcount) and create your switch tehre and call this methods from button onclick methods
private void setText() {
switch (systemcounter) {
case (0):
Text_set1.setText("Thermodynamics is the branch of physics that deals with the relationships between heat and other forms of energy.");
previous_button.setVisibility(View.INVISIBLE);
break;
case (1):
Text_set1.setText("Hi there");
previous_button.setVisibility(View.VISIBLE);
break;
case (2):
Text_set1.setText("How are you");
previous_button.setVisibility(View.VISIBLE);
break;
case (3):
Text_set1.setText("How old are you?");
break;
default:
Text_set1.setText("OPS");
break;
}
}
and call this method in your listeners (like this)
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter + 1;
setText();
}
});

changing the text of the button onclick

change the text of the button once clicked to P then again that same button is clicked the text should change to A then again the same button is clicked the text should change to H then again when the button is pressed the text should change to L in android Studio how c
final Button button = (Button) findViewById(R.id.number);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (curr) {
case 0:
button.setText("P");
curr = curr + 1;
break;
case 1:
button.setText("A");
curr = curr + 1;
break;
case 2:
button.setText("H");
curr = curr + 1;
break;
case 3:
button.setText("L");
curr = 0;
break;
}
}
});
This will work 100%
public class MainActivity extends AppCompatActivity {
private int current = 0;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (current){
case 0:
button.setText("P");
current = 1;
break;
case 1:
button.setText("A");
current = 2;
break;
case 2:
button.setText("H");
current = 3;
break;
case 3:
button.setText("L");
current = 0;
break;
}
}
});
}
}
You're going to need three things for this:
A way to react to the button being clicked
A way to set and get the state of the button
A way to change the text on the button
Thankfully, these are all easy tasks.
To react to a button click, set its OnClickListener
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateButtonState();
}
});
To set and get the state of the button, we need a way of representing the state. Since you described a simple state of P -> A -> H -> L we can represent each point as an integer.
final int BUTTON_STATE_P = 0;
final int BUTTON_STATE_A = 1;
final int BUTTON_STATE_H = 2;
final int BUTTON_STATE_L = 3;
We can then simply store the given state into a variable change this variable according to our state logic and then read whatever value the variable is at.
int buttonState = BUTTON_STATE_P;
private void updateButtonState(){
if (buttonState == BUTTON_STATE_P){
buttonState = BUTTON_STATE_A;
}
else if (buttonState == BUTTON_STATE_A){
buttonState = BUTTON_STATE_H;
}
else if (buttonState == BUTTON_STATE_H){
buttonState = BUTTON_STATE_L;
}
}
Then we just need a way of setting the text of the button depending upon what state we're in. To do this we need to know what each state looks like in terms of text.
button.setText(getTextForButtonState(buttonState));
private String getTextForButtonState(int buttonState){
if (buttonState == BUTTON_STATE_P){
return "P";
}
else if (buttonState == BUTTON_STATE_A){
return "A";
}
else if (buttonState == BUTTON_STATE_H){
return "H";
}
else if (buttonState == BUTTON_STATE_L){
return "L";
}
return null;
}
You'll notice that the most important step was step 2. You can make lots of different decisions as to how you might want to handle a state. You might decide that you want to put all of your state code into its own class and then just call methods of that class, as one suggestion.
Hope this helps.

Switching from first layout to second using layoutInflater: onclicklistner crashing the activity

In this application i am displaying 6 images randomly from an array containing drawables(named vmarray[12] ) and after 1 minute(using runnable postdelayed) switching is performed to another layout containing a single button with id BUTTON1 and setting the button background to one of the image from the earlier displayed images. I am using LAYOUTINFLATER for switching between layouts
On that button (Button1) onclick i want to do some work, but the PROBLEM IS when i implement onclicklistener and onclick method, the app crashes.
IF i remove the implements onclicklistener everything runs fine. The BUTTON1 is located perfectely through findviewbyid and its background correctly sets to an image. BUT Implementing onclicklister is crashing the app.
here is the code..
int[] vmarray= {R.drawable.vm1bulb, R.drawable.vm2chair, R.drawable.vm3comb,
R.drawable.vm4cycle,R.drawable.vm5dairy,R.drawable.vm6fan,R.drawable.vm7mobile,
R.drawable.vm8pen,R.drawable.vm9shoes,R.drawable.vm10toothbrush,
R.drawable.vm11bangle, R.drawable.vm12watch};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
setContentView(R.layout.cacrvisualmem);
firstview =(LinearLayout)this.findViewById(R.id.firsthumlayout);
secondview = (LinearLayout) inflater.inflate(R.layout.cacrvisualmempart1, null);
for(int i=0;i<6;i++)
{
final int a = i;
button_var[a] = (Button)findViewById(idArray[a]);
}
// IN FIRST LAYOUT, THERE ARE 6 BUTTONS AND THEIR BACKGROUND IS RANDOMLY SET
// DRAWABLES FROM ARRAY "vmarray". the following code is for that
Random randomGenerator = new Random();
Random rand6 = new Random();
while (numbers.size() < 6) {
random1 = randomGenerator.nextInt(12);
random2 = rand6.nextInt(6);
if (!numbers.contains(random1) && (!numbers2.contains(random2)))
{
numbers.add(random1);
numbers2.add(random2);
b[random2].setBackgroundResource(vmarray[random1]);
count++;
}//if ends
}//while ends
Handler changeview = new Handler();
Runnable r1 = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
// NOW, here, after 1 minute, second view will be inflated and button1
// background is set to one the image from the array
setContentView(secondview);
b11=(Button)findViewById(R.id.button1);
queryrandvar=queryrand.nextInt(12);
switch(queryrandvar)
{
case 0:
b11.setBackgroundResource(vmarray[0]);
queryval=0;
break;
case 1:
b11.setBackgroundResource(vmarray[1]);
queryval=1;
break;
case 2:
b11.setBackgroundResource(vmarray[2]);
queryval=2;
break;
case 3:
b11.setBackgroundResource(vmarray[3]);
queryval=3;
break;
case 4:
b11.setBackgroundResource(vmarray[4]);
queryval=4;
break;
case 5:
b11.setBackgroundResource(vmarray[5]);
queryval= 5;
break;
case 6:
b11.setBackgroundResource(vmarray[6]);
queryval= 6;
break;
case 7:
b11.setBackgroundResource(vmarray[7]);
queryval= 7;
break;
case 8:
b11.setBackgroundResource(vmarray[8]);
queryval= 8;
break;
case 9:
b11.setBackgroundResource(vmarray[9]);
queryval= 9;
break;
case 10:
b11.setBackgroundResource(vmarray[10]);
queryval= 10;
break;
case 11:
b11.setBackgroundResource(vmarray[11]);
queryval= 11;
break;
}//switch ends
}//run ends
};//runnable ends
b11.setOnClickListener(null);
changeview.postDelayed(r1,10000);
} //on create method ends here
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
{
b11.setBackgroundResource(vmarray[1]);
break;
}
}//switch ends
}//onclick ends
i got it.inside runnable after switch case i have put the following and button onclick is working.RUNING FINE WITH NO APP CRASH
b11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b11.setBackgroundResource(vmarray[0]); //SOME RANDOM IMAGE FOR CHECKING
}
});

Trying to code my first app, but the buttons arent working

So Im trying to make a simple Tip Calculator as my first app. I watched multiple tutorials, but for some reason, I cant get the buttons to work. The slider works fine so Im not sure what the issue is.
From what I understand, this is where I setup each button threw an array.
int idList[] = {R.id.button1,R.id.button2,R.id.button3,
R.id.button4,R.id.button5,R.id.button6,
R.id.button7,R.id.button8,R.id.button9,
};
for (int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
and here is where I use them
private class ButtonclickListener implements View.OnClickListener{
public void onClick (View v) {
switch (v.getId()){
case R.id.buttonC: //clear
Scr.setText("0");
NumberBf = 0;
break;
case R.id.button_tip:
CalcTip();
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
In your list, you are using R.id.button1
But in your switch case you are using different IDs (R.id.buttonC)?
it should be
int idList[] = {R.id.button1,R.id.button2,R.id.button3,
R.id.button4,R.id.button5,R.id.button6,
R.id.button7,R.id.button8,R.id.button9,
};
for (int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
case R.id.button1: break; case R.id.button2: break;
In short when it should match when you do listener and findviewbyID

Android Mapping Remote Control Keys with Virtual Key Board and append the text in edittext

I am working on a project based on Mapping the Remote control keys with android device.Here I can able to get the keycodes of Remote keys and return values for it based on the key codes.But the problem is, I don't know how to append the values inside the edit text.If I pressed the remote keys, it always returns numbers only.Guide me in a right way to make this work. Thanks in advance.
Sample Code:
I am having the below code in a Global Activity.And I extended all other Activities from this one.
public String switchedMethod(int key)
{
String letter = null;
switch(key)
{
case 9:
letter = "a";
break;
case 10:
letter = "b";
break;
case 11:
letter = "c";
break;
case 12:
letter = "d";
break;
case 13:
letter = "e";
break;
case 14:
letter = "f";
break;
case 15:
letter = "g";
break;
case 16:
letter = "h";
break;
}
Log.v("LETTER", ""+letter);
return letter;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
Log.v("KEYCODE", ""+keyCode);
switchedMethod(keyCode);
return super.onKeyDown(keyCode, event);
}
//Code Related to Edit Text
public class SettingsSubElementCreator extends GlobalActivity
{
protected void handleSDEditText(int optionItemsCurrentItemIndex)
{
LinearLayout subLayout = new LinearLayout(this);
subLayout.setOrientation(LinearLayout.VERTICAL);
subLayout.removeAllViews();
createButtons();
// I NEED TO APPEND THE TEXT FOR THE BELOW EDITTEXT VIEW
final EditText SDEditText = new EditText(this);
SDEditText.setTypeface(boldTypeface);
subLayout.addView(SDEditText);
subLayout.addView(okcancelButtonLayout);
final ModifySettingsDialog dialog = new ModifySettingsDialog(this,
R.string.video_aspect_adjustment_sd,
optionItemsCurrentItemIndex, subLayout, false);
dialog.show();
okButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(view.getContext(),"inside video aspect adjustment sd"+ SDEditText.getText(), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
}

Categories

Resources