I have a class called TouchImageView extends ImageView and I detect where the user clicks on it. If it is a interest point, I want to call a method on the Detailed_Image_Activity that will update a WebView. How can I achieve this?
I found some ideas about using observer and observables but I don't know how to do that. I found this solution Equivalent of iOS NSNotificationCenter in Android? but I can't make it work it
This is my code in the TouchImageView class...
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(isPointOfInterest) {
//The code below is used to update the WebView
//The task called below exists in the Detailed_Image_Activity
DownloadHighlightBackground HighlightDownloaderTask = new DownloadHighlightBackground();
HighlightDownloaderTask.execute(new String[] { arg1.toString() });
}
}
Try this,
You can get the activity from within the view, in this way..
((MyActivity)getContext()).method_name();
To start up an activity you need access to the application's context and then you can call startActivity.
Related
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.
I'm fairly new to android studio, any help would be appreciated.
I have set up a bottom navigation bar programatically in my MainActivity - what's the best way to set this up with other fragments. I have three fragments, one for each tab in the navigation bar and other fragments which can be opened when buttons are pressed from the navigation bar fragments.
Where do I set up these other fragments? in the same activity that connects the fragments that are connected to the navigation bar or in a different activity.
How do I save the current state of the displayed fragment so that when I move to a different tab and then move back it will be in the same state as when I left it?
My question is, where do i set up these other fragments? in the same activity that connects the fragments that are connected to the navigation bar or in a different activity.
It's really up to you and how you want to display the fragments. You can display them in the same activity or open another activity. However bear in mind that if you open another activity, you will lose the navigation bar of the previous activity (an activity always uses the whole screen)
What does FragmentManager and FragmentTransaction exactly do?
How do I save the current state of the displayed fragment so that when
I move to a different tab and then move back it will be in the same
state as when i left it?
Read about the fragment lifecycle at https://developer.android.com/guide/components/fragments.html#Lifecycle
Specifically, you want to save your state in onSaveInstanceState, and the stuff you save will be sent back to you when the fragment is recreated in onCreate
I'd like to expand on what #rupps said, because I feel like the part about what do FragmentManager/Transaction do is not approached from where you are expecting.
I assume you're using a BottomNavigationView.
Regardless of the (important) lifecycle of Fragments, you have to understand that a Fragment is always attached to an activity (note: this is not true, but let's not talk about headless fragments for now).
The approach you can take is that the Activity layout looks like this: (in pseudo code)
<RelativeLayout width=match_parent height=match_parent>
<FrameLayout
id="#+id/your_fragment_container"
width=match_parent
height=match_parent
layout_above="#+id/navbar" />
<BottomNavigationView
id="#id/navbar"
width=match_parent
height=wrap_content
align_parent_bottom=true />
</RelativeLayout>
This way the BottomNavBar will always be present at the bottom of your layouts.
Now you have to deal with putting the fragments there… Let's say that you need to attach a Listener to that bar, and when you receive a callback that a new menu item has been selected… you can proceed to change the fragment (you will always get one event upon startup or you can force it during onCreate I suppose).
You will literally add a switch/if statement to the onNavigationItemSelected(MenuItem item) method.
and call addFragment(TAG); depending which case it is.
Pseudo-Code for you to get the idea:
private void addFragment(final String tag) {
final Fragment existing = getSupportFragmentManager().findFragmentByTag(tag);
if (existing == null) {
final Fragment newInstance = getNewFragmentInstanceWithTag(tag);
getSupportFragmentManager()
.beginTransaction()
.replace(getFragmentContainerLayout(), newInstance, tag)
.commit();
}
}
You'll also need to provide:
private int getFragmentContainerLayout() {
return R.id.your_fragment_container;
}
and…
public static final String TAB1_TAG = "TAB1_TAG";
public static final String TAB2_TAG = "TAB2_TAG";
public static final String TAB3_TAG = "TAB3_TAG";
protected Fragment getNewFragmentInstanceWithTag(String tag) {
switch (tag) {
case TAB1_TAG:
return Tab1Fragment.newInstance();
case TAB2_TAG:
return Tab2Fragment.newInstance();
case TAB3_TAG:
return Tab3Fragment.newInstance();
default:
return null;
}
}
So what the frog is the FragmentManager/Transaction?
Think of the Manager as a singleton object (one per app) that keeps a reference to your Fragments and can retrieve them for you (if they existed before). It handles Transactions (add/remove/hide/show, etc.) so you can later roll back them (say you add a fragment in a transaction, if you also addToBackStack() then you can simply tell the Manager: pop the last transaction, effectively rolling it back.
It's a monster. It had bugs for over 9000 years and it's not very intuitive; but once you get used to it, you just "use it".
Just to be clear, because my question can be not so clear.
I develop Music Player app. The thing is I have MainActivity and 4 Fragments in this activity(it's not all).
In each fragment I have list of songs retrieved from device using CustomCursorAdapter(for example: first fragment - all songs, second fragment albums e.t.c.)
I already tried to use MediaPlayerSingleton
public class singletonMediaPlayer{
MediaPlayer mediaPlayer;
private static singletonMediaPlayer in = null;
private singletonMediaPlayer() { }
public static singletonMediaPlayergetInstance() {
if (in == null) {
synchronized (singletonMediaPlayer.class) {
if (in == null) {
in = new singletonMediaPlayer();
}
}
}
return instance;
}
}
But here the problem was that all playback controls I have in MainActivity(not in fragments) and have no idea how to handle previouse, next buttons. It is not a problem if media player is in fragment or activity together with ListView of songs but like this... have no idea. Plus when I tried to select item(song) from another activity it just didn't play until I press play button. Playbacks I can see it through all fragments so it's looks like this(just in case):
Plus I have 2 seperate Activities to show songs from albums and from playlists. Sooooooooooo... Finaly the question is:
How do you think it is better to build Media Player for such app (just in case, I don't need code from you). Is it better to use Music Service(which I already started to build) or maybe Singletone is better(in that case I just don't know how to perform the task with singletone for now) or maybe there is another way??? Will be great if somebody response with hint, link or just show me the way in which better to go.
Thank you in advance!
P.S.
Yep, by the way there are 3 ListViews with songs(for now) - 2 of them reusable.
totally n00b in android programming with an embarrassing question, here it goes. For example, I have an onClick function with a view parameter like this:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
If I have to call this function in an another class in the same activity for example an AsyncTask class or whatever. How would I successfully do that? I have confusion with the parameter. Should I do it like:
View view; //local variable
onRadioButtonClicked(view); // it gives an error of being uninitialized
Or should I initialize it with a null value like:
View view = null;
//local variable onRadioButtonClicked(view); //this gives a null pointer exception
How do I call this function successfully without having a problem with the parameters?
Generally you wouldn't call your onRadioButtonClicked() method yourself. The way you should use this in android is to set the onClick attribute in your xml like so onClick:onRadioButtonClicked. This way the android operating system will call the method for you when the user clicks the button.
The way android handles events like button presses is to use a callback method. Your callback for the radio button can be set programatically by calling radioButton.setOnClickListener() and passing in a radioButtonOnClickListener that you would create yourself. It can also be set in the xml as stated above. If you have a method like that in your class you should declare the onclick in the xml.
Read this for onclick for views in general
http://martin.cubeactive.com/android-onclicklitener-tutorial/
and here is some example radioButtonCode so you can see one in action
https://github.com/asabbarwal/SimpleRadioButton
I have 5 tabs and I want to call a function on it's longclick (onLongClick()).
The longclick is working but when I release the touch the click (onClick()) function is also called along with it.
Please anyone help me on this problem.
It happens. I also had the same problem while implementing OnItemClickListener and OnItemLongClickListener.
You can accomplish this with a vairable value:
int i=0;//declare this as outside all methods
void onClick(...)
{
if(i==0)
{//your code
}
else
{
i=0;
}
}
void OonLongClick(...)
{
//your code
i=1;
}
this won't stop onClick from being called on long click but will fulfill your purpose by not performing the task you want to perform only on onClick().
Another method is to call another activity using intent from method onLongClick(). This will stop onClick() from being called because the control will move to another activity.