I am new to programming in Java, i've managed to create a little calculator as a little test app.
But i think i am using way to much code for my needs.
So i've given a Button a name: buttonname
Now to change it's text when clicked i need to:
public class MyActivity extends Activity {
Button buttonname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
buttomname = (Buttom) findViewById(R.id.buttomname);
}
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
}
(i've bolted everything i had to add)
So i had to do everything above + connect the buttonClick through the xml file.
So i was wondering if there is a easier way to define all objects so i dont have to do: Button buttonname; and buttomname = (Buttom) findViewById(R.id.buttomname); all the time.
And i was wondering if there is a easier way to auto create button events.
(I am used to Visual Studio, but now i am kinda lost in Android Studio. So on Visual Studio i just had to double click the button and type: buttonname.Text = "NewText";)
There is a library called Butter Knife to do approximately that
However, I'm not sure if you really need it.
Oh, and you don't have to find the same Button every time. You find it once in onCreate and store in a field.
First of all you have typo in
buttomname = (Buttom) findViewById(R.id.buttomname);
It should be
buttomname = (Button) findViewById(R.id.buttomname);
and you forgot ; in one line "didn't your IDE show error to you!!" and also small correction in
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
it should be
buttomname.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttomname.setText ("NewText");
}
});
inside protected void onCreate.
2nd method:
And if you have define android:onclick="buttonnameOnClick" in XML then
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
To be corrected to
public void buttonnameOnClick(View v) {
buttomname.setText ("NewText");
}
You can do it in a loop if you have a lot of identical buttons to process
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
for (int btn_id : new int[]{
R.id.buttomname
, R.id.buttomname2
, R.id.buttomname3
}) {
View v = view.findViewById(btn_id);
if (v != null) {
v.setOnClickListener(onClickButton);
}
}
}
//
private View.OnClickListener onClickButton = new View.OnClickListener() {
#Override
public void onClick(View view) {
// .. handle click
if (view.getId()==R.id.buttomname2){
}
}
Your code is partly correct,
however the
(Buttom) is wrong change it to (Button)
the other thing
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
can just be changed to:
public void buttonnameOnClick(View v) {
Button buttonTemp = (Button)v;
buttonTemp.setText ("NewText");
}
Assuming you are calling the method from layout xml file.
you must use the onClickListener() method for Button object.
Your code like this structure;
buttonname = (Button)findViewById(R.id.buttonname);
buttonname.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I recommend to your visit Button | Android Dev page for Button.
Related
How do I change the color of the background randomly with a button press in Android studio?
Here is my code:
public class partymodus extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partymodus);
final TextView aufgabe=(TextView)findViewById(R.id.txt_aufgabe);
final Button next = (Button)findViewById(R.id.btn_next);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String[] aufgaben = getResources().getStringArray(R.array.name);
Random rand = new Random();
int n = rand.nextInt(aufgaben.length - 0) + 0;
aufgabe.setText(aufgaben[n]);
}
});
}
You have to add an ActionListener to your button and override the method:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
And sorry for my english i'm beginner
As an un-profession to answer your question, you have to digging out what is jave graphic design pattern is before goes in official API,
Here is a link to search the JFrame or Java.awt.Graphic, [1]
it't where you start to build the components on the graphic,since you are building with a button component, I may suggest you looking the Inherit or father interface of JFrame, and another Containers
MyActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyActivity.setBackgroundColor(getResources().getColor(R.color.RED));
}
add view_name.setBackgroundColor(getResources().getColor(R.color.colorAccent));
line to set background color
this is my code:
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mHomeLl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
});
I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;
Hey so I'm trying to make a simple code that makes the visibility of a layout visible once an image been clicked twice or more.
Sadly my code doesn't work, but I don't understand why.
Here's my code -
public class MainActivity extends AppCompatActivity {
ImageView logoIMG;
LinearLayout adminLinear;
int cnt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoIMG = (ImageView) findViewById(R.id.logo);
adminLinear = (LinearLayout) findViewById(R.id.adminLinear);
adminLinear.setVisibility(View.INVISIBLE);
adminLinear.setEnabled(false);
while (adminLinear.getVisibility() != View.VISIBLE) {
logoIMG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cnt >= 2) {
adminLinear.setVisibility(View.VISIBLE);
adminLinear.setEnabled(true);
} else {
cnt++;
}
}
});
}
}
}
Setting onClickListener in your while loop, will endlessly loop and keep on trying to add new Listener, which will cause issue.
Do following:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
logoIMG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cnt >= 2) {
adminLinear.setVisibility(View.VISIBLE);
adminLinear.setEnabled(true);
} else {
cnt++;
}
}
});
}
Your code just gets stuck in an infinite loop. Setting an onClickListener once is enough. Remove the loop around setOnClickListener altogether, or at least replace it with a conditional (if).
"The first click just sets the focus to the Image then the second click actually gets handled as a click. "
try setting android:focusable="false" or true. vice versa
Check this Question
I know my question might be stupid but I am new in Android App development and the Eclipse things but reached to e problem that can't find solution in internet.
I am making multi-activity application and reached to a point where when i have two buttons in one of the activities and want each of them to lead to different other activities, the application crashes. When I lead them both to one activity, everything is fine. Here is my code and hope really my question not to be so stupid as I am thinking.
public class Home extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button myButton = (Button) findViewById(R.id.tables);
myButton.setOnClickListener(goToTables);
Button mySecondButton = (Button) findViewById(R.id.reservations);
mySecondButton.setOnClickListener(goToMenu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
private OnClickListener goToTables = new OnClickListener(){
#Override
public void onClick(View v) {
doButton();
}};
private void doButton()
{
startActivity(new Intent(this, Tables.class));
}
private OnClickListener goToMenu = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
doSecondButton();
}};
private void doSecondButton()
{
startActivity(new Intent(this, Menu.class));
}
}
The goToTables works perfectly but I am missing something important to change in goToMenu. My other activities are: Tables and Menu. Can somebody please tell me where I am wrong? Thanks in advance!
android:onClick="dobutton" try adding this in your button tag in xml code rather then using onclicklistner.
Try changing the name of your Menu activity or add the full name path of Menu.class in your intent, eg. com.myapp.Menu.class
PLESAE NOTE: The solution to my problem is in bold text at the bottom. I accepted Melquiades's answer because he helped me filter out everything that could have been the problem. It turns out, I was the problem, not android or anything else. So if you are looking for the answer, read below.
I'm trying to save the state of a variable as it is before onPause(); , onStop(); , onDestroy(); are called.
The book I am using has me override a method called
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, myIntVaraible);
}
the variables you see in the parameter are declared at the beginning of the class
private static final String KEY_INDEX = "index";
private int myIntVariable;
with this method created, the book tells me to then go the the onCreate method and add
if(savedInstanceState != null){
myIntVariable = savedIntanceState.getInt(KEY_INDEX, 0);
}
But this does not work.
Whenever the activity is destroyed and created, the myIntVariable is reset to 0.
What I did to fix this is I went to my manifest file and
added android:configChanges="orientation|screenSize".
However, I have read that this is not practical and is strongly advised against.
EDIT: As suggested, I am adding my onCreate(); and onResume(); methods..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate()");
setContentView(R.layout.activity_main);
iterateQuestions();
mTrueButton = (Button)findViewById(R.id.trueBt);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correctPressed = true;
checkForTrue();
}
});
mFalseButton = (Button)findViewById(R.id.falseBt);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
falsePressed = false;
checkForFalse();
}
});
mNextButton = (ImageButton)findViewById(R.id.nextBt);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter++;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}
catch(Exception e){
iterateQuestions();
}
}
});
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
mTextViewQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter++;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}
catch(Exception e){
iterateQuestions();
}
}
});
mPrevButton = (ImageButton)findViewById(R.id.prevBtn);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter--;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}catch(Exception e){
iterateQuestionsReverse();
}
}
});
}
and
#Override
public void onResume(){
super.onResume();
Log.d(TAG,"onResume()");
}
For all intents and purposes, the variable mIndexCounter is the "myIntVariable" I mentioned.
SOLUTION: I was using a book and unfortunately, since I am new to android programming, relied too much on the code written in the book. The authors usually add new code in their book as bold, black text. This time, they failed to do that and I had trouble figuring out why my data was not being saved. It turns out that it was saved all along, I just failed to update the view with the saved data whenever it was retrieved. After adding 3 lines of simple code, my mistake was obvious and the goal I had been trying to accomplish, a success.
My program displayed a string of text that was dependant on an int that was used to retrieve information from the R.java class. After launching the app, when the user presses Next, the data changes because the int is incremented and the String on the view changes.
This data was to be saved due to the nature of android destroying any unsaved data upon orientation change.
All I had to do was simply add the saved data, an int, the same way I used to display this string/text in the first place. Instead, I foolishly assumed it would do it automatically because the book did not add this code and I relied on it too much.
This was a great learning experience and if anyone ever comes across something like this, feel free to email me if my answer is not clear.
Instead of in onCreate(), restore your variable in onRestoreInstanceState():
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myIntVariable = savedIntanceState.getInt(KEY_INDEX, 0);
}
The docs also say:
Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.
Btw, change your onCreate() signature to:
#Override
protected void onCreate(Bundle savedInstanceState) {
as in the docs.
Try this:
android:configChanges="keyboard|keyboardHidden|orientation"
As stated here