I get an error for a very simple thing. I have created a test button and an onClick method to just change the layout. I did it in a simple way so you could understand my problem better.
This is my button method:
public void accountButton (View v){
setContentView(R.layout.activity_start);
}
And this is the xml file of my button:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:id="#+id/button"
android:layout_below="#+id/welcomeTxt"
android:layout_centerHorizontal="true"
android:layout_marginTop="149dp"
android:onClick="accountButton"
android:nestedScrollingEnabled="true" />
I get the following error when i click the button:
java.lang.IllegalStateException: Could not find method
accountButton(View) in a parent or ancestor Context for
android:onClick attribute defined on view class
android.support.v7.widget.AppCompatButton with id 'button'
You may be calling your setContentView method from another activity. This method inflates the layout.
If it's called outside the activity the layout belongs to, the button won't be found. The most common way to initilize an activity from another is by intent.
Intent intent = new Intent(this, StartActivity.class);
startActivity(intent);
And then, inside your activity you call setContentView(R.layout.your_activity_layout) to inflate the layout. If you do this, you can call the onClick(View view) referred in the xml file from inside your activity normally.
For those that still have issues, in Android Studio or Intellij IDE, this is likely to a cached version of the class you are using (or its predecessors), that is not being recompiled.
Do an "Invalidate Cache/restart" and your problems are likely to go away.
When I had this issue occur repeatedly, I noticed that it was due to a "File Lock", triggered by Google Drive, that was making a copy of my File(s). Temporary disabling that solved all my issues.
you should not call setContentView(R.layout.activity_start); inside onClick() mentod of button.you have to call setContentView(R.layout.activity_start); inside oncreate() method.
follow the steps to achieve it.
implement OnClickListener in your class
initialize the button in onCreate()
Button button = (Button) findViewById(R.id.button);
set the setOnClickListener() method for button
btn.setOnClickListener()
then call the method outside of oncreate()
public void accountButton (View v){ //do some thing which you want }
Related
I've started working on a menu for my app and I'm trying to start an activity from a fragment. My fragment code looks like this;
public class Studies extends Fragment {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Studies");
}
public void goToAttract(View v) {
Intent intent = new Intent(getActivity(), informaticainfo.class);
startActivity(intent);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.studies, container, false);
}}
I've got this working in a different project so I do not think that is the problem, my XML button to go to the next activity looks like this;
<Button
android:id="#+id/I"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="40dp"
android:background="#drawable/buttonshape"
android:onClick="goToAttract" <---- is this wrong?
android:paddingLeft="130sp"
android:paddingRight="130sp"
android:text="#string/informatica"
android:textColor="#ffffff" />
I've declared the new activity in the Manifest, but the XML file keeps giving this error at the line specified above;
Cannot resolve symbol 'goToAttract' less
Inspection info: Checks if the method specified in onClick XML attribute is declared in related activity.
Does the method I'm using above not work with fragments? Why can it not find the function I have working in another project?
Check this link [How exactly does the android:onClick XML attribute differ from setOnClickListener?
According to this that with the XML above, Android will look for the onClick method only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.
Declaring and assigning value to onClickin XML does not work in fragment, use OnClickListener programmatically instead of using onClick in XML.
I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.
In android Studio, I want when i click on button , next activity/fragment should come from right side and present activity sholud gone left.I implimented its working on Activity but not on adapters is showing error.
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
startActivity(i);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
overridePendingTransition is working on Activity but not working on Adapters of Recyclerview and Listview, Please tell any other option. I want when i click on recyclerview item next Activity should navigate or come from right side by using overridePendingTransition.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
Utils.addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
This tip features how to change Android’s default animation when switching between Activities.
The code to change the animation between two Activities is very simple: just call the overridePendingTransition() from the current Activity, after starting a new Intent. This method is available from Android version 2.0 (API level 5), and it takes two parameters, that are used to define the enter and exit animations of your current Activity.
Here’s an example:
//Calls a new Activity
startActivity(new Intent(this, NewActivity.class));
//Set the transition -> method available from Android 2.0 and beyond
overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
These two parameters are resource IDs for animations defined with XML files (one for each animation). These files have to be placed inside the app’s res/anim folder. Examples of these files can be found at the Android API demo, inside the anim folder.
for example code visit http://www.christianpeeters.com/android-tutorials/tutorial-activity-slide-animation/#more-483
Change like this code you must be passing activity as context in adapter
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
Activity activity = (Activity) context;
activity.startActivity(i);
activity.overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
Note : Context is the Base Object of Activity
Update :
I have checked the accepted answer but hope you understand that it will be called everytime when your activity get launched and thats not supposed to be best practice. I am suggesting better approach if you want to follow the accepted answer .
Alternative :
Pass one parameter in bundle to new activity to make sure that transition coming from that specific adapter so double transation should not happen when you are coming rom any other activity also.
There is a easy way to do this. just put overridePendingTransition on your OnCreate method of next Activity/Fragment.So that when next Activity will come it will come according to your choice.Need not add overridePendingTransition on adapters.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ask_question);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
I am working on an android project in which i have to add links i am following the given below example.. But when i am clicking on the link neither it is highlighting nor i am able to access the link. Clicking on the link is causing an exception which says
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I want to open the link in the browser when i am clicking on the link.How to do it efficiently?. I am expecting an answer soon !Thank you
NB: i am using a dynamic textview in my actual project
public class StackOverflowActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView link = new TextView(getApplicationContext);
String linkText = "Visit the <a href='http://stackoverflow.com'>StackOverflow</a> web page.";
link.setText(Html.fromHtml(linkText));
link.setMovementMethod(LinkMovementMethod.getInstance());
}
Use android:autoLink="web" in your TextView xml. And if it does not work, try android:linksClickable="true"
Based on your error, if using dynamic TextView make sure you refer your view with this object as
TextView yourView = new TextView(this);
this refers to your Activity context where I think you might have made a little mistake.
You should not use getApplicationContext for creating a view with Activity context.
I believe you have to inflate the layout that contains your TextView before you can use it, like so:
getActivity().getLayoutInflater()
I have this line of code:
Button button = (Button) findViewById(R.id.view);
Which gives the following error:
id cannot be resolved or is not a field
That error is logical, because I have nothing what needs an Id in R.java yet, and therefore Id is missing. This will be generated when I execute the code (because I make buttons at onCreate(), and they get Id's). But Eclipse won't let me run before I fix the problem. So is it safe to add this line of code to R.java:
public static final class id {
}
Or maybe there is another sloution?
If you create buttons in onCreate, they aren't added to the resources. The resources are fixed from the moment you build your APK.
Surely if you created the button, you already have the Button object and don't need to look for it in the resources anyway?
No. Anything you add to R.java will get deleted the next time you build. It is an auto-generated file.
You cannot append R.java. But if there is anything that you want to add you can create another file of your own (like Rcustom.java), keep your stuff in it and import it wherever you use it.
findViewById() is used when you are referencing an XML layout that was usually set by setContentView(), or inflated with LayoutInflater.
So if you have a Button in your main.xml layout, with the id of "view", you would do the following in your Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.view);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Respond to click here
}
});
}