I created a normal button in main.XML and in Java I added added a Toast message when clicking it. My problem is I need to hide it when clicked, but that involves R.id.main or something like that. The problem is I get the error "Unknown entity 'id'". Am I missing imports?
Imports:
package com.redstonelamp.DroidRedstoneLamp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View. *;
Code:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void confirmClicked(View view){
Toast.makeText(getApplicationContext(), "Please choose a version to download",
Toast.LENGTH_LONG).show();
}
}
If you want to hide your button you have two possibilities :
1. With a Listener
Let's say you have this XML file :
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In your main class you will need to retrieve your Button and subscribe your MainActivity to the click event of this button.
MainActivity
public class MainActivity extends Activity implements View.onClickListener
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// this will inflate all the UI elements you have added
// in your main.xml file
setContentView(R.layout.main);
// here you retrieve the button in the layout by its ID
Button myButton = findViewById(R.id.my_button);
// here you tell your button he should propagate the
// Click event to this Activity.
myButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
// here you handle the click
// the view parameter is the view that was clicked
// therefore your button :)
// so all you have to do is to set it's visibility
view.setVisibility(View.INVISIBLE);
}
}
2. Directly by naming the method
The mechanism behind is the same but this one allows you to have a custom method name. To do this you will have to add a field in the XML file named : onClick.
This field will contain the name of the method that will handle the click.
This method has to be implemented in the Activity / Fragment in which you have inflated this Button (with the setContentView method).
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myOnClickMethod" />
</LinearLayout>
Then in your MainActivity :
MainActivity
public class MainActivity extends Activity implements View.onClickListener
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// this will inflate all the UI elements you have added
// in your main.xml file
setContentView(R.layout.main);
}
public void myOnClickMethod(View view)
{
// here you handle the click
// the view parameter is the view that was clicked
// therefore your button :)
// so all you have to do is to set it's visibility
view.setVisibility(View.INVISIBLE);
}
}
Hope this will help you.
Cheers
Related
I have a weather app that requires you to take the text from a edit text field and display it in a text view, I'm trying to make it so when I enter a place it will generate random weather for them along with displaying their input.
I haven't tried much apart from examples online as I recently started learning android development.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* Implementation for the main activity
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// member variable for the user provided location
private String location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the Get Forecast button
Button btnGetForecast = (Button) findViewById(R.id.btnGetForecast);
// set the click listener to the btnGetForecast Button
btnGetForecast.setOnClickListener(this);
EditText loc = findViewById(R.id.etLocationInput);
location = loc.getText().toString();
}
#Override
public void onClick(View view) {
// view is the View (Button, ExitText, TextView, etc) that was clicked
// if it was the btnGetForecast
if (view.getId() == R.id.btnGetForecast){
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvTitle" />
<TextView
android:id="#+id/tvInstructions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter a location below for the forecast" />
<EditText
android:id="#+id/etLocationInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/btnGetForecast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Forecast" />
<TextView
android:id="#+id/tvLocationDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="The weather in " />
</LinearLayout>
I expect the app to show input from user and display it in text view
This line in your onCreate: 'location = loc.getText().toString()' will only get the current text in loc, which at onCreate will be an empty string.
You should look into TextWatcher: https://developer.android.com/reference/android/text/TextWatcher. This will allow you to get a callback when the text of loc changes and you can then carry out your weather generation.
Well, all you need to do is to add this code in onClick method:
#Override
public void onClick(View view) {
// view is the View (Button, ExitText, TextView, etc) that was clicked
// if it was the btnGetForecast
if (view.getId() == R.id.btnGetForecast){
String text = loc.getText().toString();
yourTextView.setText(text);
}
}
And don't forget to make view variables global, so you could access them outside onCreate method, without using findViewById() again.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView yourTextView;
private EditText loc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the Get Forecast button
Button btnGetForecast = (Button) findViewById(R.id.btnGetForecast);
// set the click listener to the btnGetForecast Button
btnGetForecast.setOnClickListener(this);
loc = findViewById(R.id.etLocationInput);
yourTextView = findViewById(R.id.tvLocationDisplay);
}
...
}
I've been dealing with this problem for awhile and have looked at all the relevant questions I could find, such as: this one, this one, and this one. Could you help me correct this error? It's the only one being thrown by the logcat.
java.lang.IllegalStateException: Could not find method playPauseMusic(View) in a parent or
ancestor Context for android:onClick attribute defined on view class
android.support.v7.widget.AppCompatImageButton with id 'playPause'
Relevant code:
radio.java
package com.example.jacob.wutk;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.io.IOException;
public class radio extends AppCompatActivity {
/** Called when the user touches the button */
public void playPauseMusic (View view, final ImageButton playPause) throws IOException {
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
mediaPlayer.start();
}
});
playPause.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
playPause.setImageResource(R.drawable.play1);
} else {
playPause.setImageResource(R.drawable.pause1);
}
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
}
}
activity_radio.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:context="com.example.jacob.wutk.radio">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|center_vertical"
android:scaleType="centerCrop"
android:src="#drawable/background_mic1"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip">
<ImageButton
android:id="#+id/playPause"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="?android:selectableItemBackground"
android:clickable="true"
android:onClick="playPauseMusic"
android:scaleType="fitCenter"
android:src="#drawable/play1"/>
<ImageView
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:layout_marginRight="5dp"
android:layout_weight="1.0"
android:background="?android:selectableItemBackground"
android:scaleType="fitCenter"
android:src="#drawable/logo"/>
</LinearLayout>
</FrameLayout>
Defining onClick in xml means you need to define it for a particular view here is ImageButton you can not have two arguments in that method.
Your error is also saying that Could not find method playPauseMusic(View) means compiler needs a public method with single parameter View, whereas you were having two parameters: View & ImageButton.
This is the reason why you where getting that error. Just remove one argument from the method and it will work.
Do it like this :
public class radio extends AppCompatActivity {
/** Called when the user touches the button */
public void playPauseMusic (View playPause) {
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
mediaPlayer.start();
}
});
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
((ImageButton)playPause).setImageResource(R.drawable.play1);
} else {
((ImageButton)playPause).setImageResource(R.drawable.pause1);
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
}
}
One more thing writing android:onClick="playPauseMusic" means the method playPauseMusic will be called on Button click so you have already defined a button click so no need to define it inside the method by playPause.setOnClickListener so I have removed that code.
Your code possibly should start with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
}
You're specifying onClick in xml
android:onClick="playPauseMusic"
So, the method works, you've got inner onClicks too. If they are some views.
You gotta initialize and get it from the xml in code, for ex-
If you have ImageButton in xml, whose id is "playPause"
ImageButton playPause; //Declare it here if you wanna use it in all other places in the class or outside of your class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playPause = (ImageButton)findViewById(R.id.playPause);
playPause.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
//OnCLick Stuff
}
});
}
In Your case, you've got onClick attribute in xml and another onCLick in code. You Use one.
The question is already answered but I hope this will help someone like me in the future. I was having this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test1, PID: 6892
java.lang.IllegalStateException: Could not find method btnClickStartThread(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.MaterialButton with id 'btnStartThread1'
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:447)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:405)
After struggling a lot I got it fixed by going to layouts and I realized I had two layouts:
activity_main.xml
activity_main.xml (v21)
My changes were just reflecting on one and the app was loading other version of layout.
As suggested here
Android Studio not deploying changes to app
I have written UI functions in the MainActivity.java (shown below). Now, due to design issues, my requirement is to separate these functions from MainActivity.java and write into other file and, then these functions will interact with UI elements. How can I separate UI functions from MainActivity.java.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// There is "Off" button On UI. Onclick event of the button, this function
// is called.
public void OffCommandInterface(View view) {
}
// There is "SetTemp" button On UI. Onclick event of the button,
//this function reads data from textbox and send data to other module.
public void SetTempCommandInterface(View view) {
}
// There is "SetTemp" button On UI. Onclick event of the button,
//this function reads data from textbox and send data to other module.
public void profileRequestInterface(View view){
}
}
I am attaching activity_main.xml file for the reference.
<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:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:onClick="profileRequestInterface"
android:text="#string/button_send" />
</LinearLayout>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Switch Off Heater"
android:onClick="OffCommandInterface" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/edit_temp"
android:layout_width="136dp"
android:layout_height="wrap_content" >
</EditText>
<Button
android:id="#+id/temp"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:onClick="SetTempCommandInterface"
android:text="SetTemp" />
</LinearLayout>
</LinearLayout>
As you declared your Button's onClick as part of layout xml its hard to separate out from Activity class scope.
When you declare your view's onClick as layout xml, it will attached with the Activity who called setContentView() on that layout. So you have to define your all Button's click method in Activity itself.
Now If you want to separate out this logic as design pattern issue, than remove onClick from xml layout file, create custom onClick listener as different java class and override onClick in that class, define your button's in onCreate() of Activity and set custom onClick listener to those buttons.
Example: (This is the just example, you can change with your code and use case)
public class CustomOnClickListener implements View.OnClickListener{
private Context appContext;
public CustomOnClickListener(Context context)
{
appContext = context;
}
#Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.button1:
// There is "Off" button On UI. Onclick event of the button, this function
// is called.
break;
}
}
}
Now, in your Activity,
public class MainActivity extends Activity {
Button buttonOff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOff = (Button)findViewById(R.id.button1);
buttonOff.setOnClickListener(new CustomOnClickListener(this));
}
You can start by removing android:onClick from your XML and handling it in the code. I never understood this practice other than for learning purposes. This should get you started.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
this.OffCommandInterface();
break;
default:
break;
}
private void OffCommandInterface() { }
private void SetTempCommandInterface() { }
private void profileRequestInterface() { }
}
Hello I want that my methods work instantly when the user enters the application.
For now I have an onClick event in my xml which activates so to say my methods(this works).
the xml:
<TextView
android:id="#+id/cd_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:paddingBottom="0dp"
android:text="time"
android:textColor="#000"
android:textSize="21sp"
android:onClick="dateEnd"/>
and Main Activity.java
String dateStopKukuk = "21 Dec 2015";
private void displayDateEnd(String etime) {
TextView priceTextView = (TextView) findViewById(R.id.cd_start);
priceTextView.setText(etime);
}
public void dateEnd(View v) {
displayDateEnd(dateStopKukuk);
}
Edit: I added a comments to explain you this code.
Try this:
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener
{
// onClick method is called when one of view is clicked. (you must use setOnClickListener on this View to inform system to call this)
#Override
public void onClick(View v)
{
// check if clicked view is cd_start
if(v.getId() == R.id.cd_start)
{
// true cd_start is clicked
displayDateEnd(dateStopKukuk);
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); // REQUIRED!!! When you don't add this your app will be crash.
setContentView(R.layout.activity_main); // sets activity_main as layout (if you use different name of layout replace activity_name with your layout name)
findViewById(R.id.cd_start).setOnClickListener(this); // finds view with cd_start id and sets click listener. When this view is clicked system calls onClick method.
// and now your code what do you want to do when activity is creating.
}
String dateStopKukuk = "21 Dec 2015";
private void displayDateEnd(String etime) {
TextView priceTextView = (TextView) findViewById(R.id.cd_start);
priceTextView.setText(etime);
}
/* You don't need dateEnd method now */
}
XML:
<TextView
android:id="#+id/cd_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:paddingBottom="0dp"
android:text="time"
android:textColor="#000"
android:textSize="21sp"
/> <!-- You don't need android:onClick -->
In your activity.
I hope it helped you.
So far I know how to change the Background's color via html codes. Now I am Trying to change the background of the Layout of my main activity to different images using a button click. If possible using only one single button.
Thank you!
The following code is from this link Setting background image in java from Omi0301.
//assuming your Layout is named linearlayout1:
LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1);
ll.setBackgroundResource(R.drawable.sample);
All you do is create a layout variable and set its background resource with the image that you would like it to be.
try to use "setImageResource" instead the "setBackgroundResourse"
Try below code
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="71dp"
android:text="changeColor" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(LinearLayout)findViewById(R.id.myLayout);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
mainLayout.setBackgroundResource(R.drawable.newImage);
}
});
}
}