I'm creating an app for the Android OS, and I'm running into a bit of a stumbling block on one issue. Here's what I want to do:
I'm currently capturing the "Back" button event just fine, but I need it to behave slightly differently, depending on the current layout the user is viewing. I have four layouts that I'm using, and if the user is on layout 1, 2, or 3, I want "Back" to take them to layout 1; but if they are on layout 4, I want them to go back to layout 3 instead.
The problem is, I can't for the life of me figure out the code that will return the id of the CURRENT layout. I'm sure this is a pretty simple problem, so I'm hoping someone will have a quick solution.
Thanks for the pointers - for some reason I'm having trouble getting getCurrentFocus() to work, though...probably due to my own ineptitude in programming Java.
I've broken it down into the following:
View thisView = getCurrentFocus();
if (thisView != null){
int viewID = thisView.getId();
toastLong(Integer.toString(viewID));
} else {
toastLong("thisView is null.");
}
The problem now is that thisView is always null - it's not returning any values. I tried putting in the activity name that I'm using in place of myActivity (making it:
View thisView = myActivityName.getCurrentFocus();
but the IDE gives me the following error and won't compile:
Cannot make a static reference to the non-static method getCurrentFocus from the type Activity.
I'm obviously missing something, and my assumption is that it's a very basic something that I'm missing. Any pointers?
I had this problem too and found a very simple solution. Though this is an old question, I'll post it here for people who are searching for help for this problem.
Just create an integer as attribute in your class:
int layoutId;
Then override the setContentView method and save the ID from the parameter:
#Override
public void setContentView(int layoutResID) {
this.layoutId = layoutResID;
super.setContentView(layoutResID);
}
Very simple trick!
You can use ViewFlipper to hold your layouts and implement a simple state machine to control transitions.
another option might be creating a separate Activity for every one of your layouts - hard to tell without exact knowledge about what your app is doing.
Related
I have the next situation - I develop the music app, it contains media service.
Also the app contains MainActivity with 4 Fragments in it. In the bottom of each Fragment there is a bar with play, skip next, skip previouse, shuffle and repeat, it looks like that:
The bar in the bottom refers to MainActivity.
Also in Albums tab and Playlist tab there are lists of albums and playlists which you can tap and it will take you to another activity with songs from taped album/playlist. I have only one service, so I bind it to all of it(one Fragment, two activities, actually I have leak but it is another problem)
The question is how can I control media playback(skipnext/previouse, play/pause, shuffle, repeat) from that bar in the bottom.
I already set OnClickListener on buttons and tried to call service method, but in that case I have an error like:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference
I tried both:
private MediaPlayerService mediaPlayerService = MediaPlayerService.getInstance()
and just in case
private MediaPlayerService mediaPlayerService = new MediaPlayerService()(of course last one doesn't work)
I tried to make mediaPlayer singleton and yes it works, but there is another problem with skipNext/Previouse - int songPosition and (ArrayList) of ids should be singleton as well (or static in the class), good, I made it, but then another problem prepareAsync called in state 1 error... W#T#F#... sorry, that is my first project and maybe I made simple things very complicated developing bycicle. Any help will be great.
Thank you.
Ok, finally I found an answer and be honest it wasn't very hard. Actually what I forgot to do is to bind service to MainActivity, after I did it, everything goes well.
So here is what my app looks like so far. Every time I click the "+" button I go into another activity where I enter description, date and time and dynamically create a horizontal LinearLayout. With the X button to the left I'm deleting said layouts with this code (I know it's not the best way but it works for me so far):
final Task toBeRemoved = x;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myLayout.removeView((ViewGroup) v.getParent());
Task.tasks.remove(toBeRemoved);
}
});
..while iterating through each element in a list where I store my values in my OnCreate method.
What I want to do now is make it so I can remove them with the assistance of the checkboxes and the "Clear" button as well.
I have added each layout dynamically, though, so I can't think of any way for me to determine which one I've checked for deletion. They have no id, they can't be stored anywhere so I can iterate through them, as far as I know. What can I do in this situation?
A couple of ways. One would be to set listeners on each new checkbox and keep a Set of views with a checked state (add to the Set when checked, remove when unchecked). Then when clear is pressed, you remove all views in that Set.
The other way is to lopp through all the child views of the parent layout above the dynamically. For each one, find the checkbox child via findViewById, and see if its check. Remove it if it is. This is computationally expensive if you have lots of complex views
I prefer method 1 myself, but either works.
I have added each layout dynamically, though, so I can't think of any
way for me to determine which one I've checked for deletion
that's not true. You can call setId( ) or setTag() while you are adding each layout,
They have no id, they can't be stored anywhere so I can iterate
through them, as far as I know. What can I do in this situation?
now they have one. You can either use findViewById or findViewWithTag
Here's a solution that I consider pretty cool.
Create a widget on your own.It's easy.
So, you would have a class that extends ...probably LinearLayout.Depends on your needs.
You create the button,the editText, the textview and the check box, than you add functionality like you want.
When the Check box is pressed, I suppose you want the X circle button to get activated and when you press it, it deletes the whole "thing".This way you won't even need the clear button.You will still need the add button though, so you can add how many of those items you need.
It's easy,practical and makes the code reusable, which is something I look for always.
If you need more help, I can help you in a bit more detail ,but I can't always be around so I am sorry if I will respond a bit slow.
As a C# developer I'm trying to get familiar with Java and more specifically, the Android framework.
I've created some very basic intro Activities, but I'm now trying trying to get a ListView up and running with 'databinding'. I found this sample code: http://developer.android.com/guide/topics/ui/layout/listview.html
I don't think I've fully grasped the concept of these views yet, because initially I figured that the ListActivity class that I created would be built as some sort of a user-control that I could simply replace my ListView with. When I look at the code though, it appears as though it's somehow trying to hook into an existing view which confuses me. (How do I call this ListActivity from my current activity, and how do I use it with my ListView?).
getListView().setEmptyView(progressBar);
Could someone please clarify what's going on? Perhaps I've become too .NET paradigm orientated and I'm not understanding the picture properly.
A ListActivity is an activity that assumes that you will set a layout with a list view in it with a certain id. It will then store that view in a variable so getListVew() will return it. Basically its a tiny bit of syntactic sugar to do what you can do yourself with 3 lines of code.
Really I don't think its worth using. You can use listviews in a regular activity, it takes 1-3 lines of code to do everything the ListActivity does, and you don't have problems if you name your listview with a different id or if you even decide to not have a listview down the road.
First of all, I want to tell you that I'm new here and I'm from Spain and my english level isn't so good, so please... try to understand me haha. Also, you must know that I'm a telematic engineering student and programming is just my favourite hobby. With this info, I just want you to be comprehensive with my question: I know that it's a rookie question and it's worse when I'm pretending to create an Android game... But I'm learning bit by bit.
PROBLEM
The problem that I have is the next one. I want to set a .PNG image in my principal activity called "*activity_principal*". This image has lot of empty space and the background is initially black (due to the theme selected at the beginning I guess). Well, this image has some details in black and them merges with the background colour.
My first solution was trying to set the two backgrounds from the XML corresponding code, but rapidly I realized it was impossible to use it twice in a same layout. So I thought that it would be fixed by the next way: I set the "android:background="#android:color/white"" in the XML file and in the .java file I set the other resource to the background:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
RelativeLayout fondo = (RelativeLayout) findViewById(R.layout.activity_principal);
fondo.setBackgroundResource(R.drawable.prototipoestructurapantalla);
}
I used to use this structure and never had problems but today, trying to do this, I noticed something strange. Due not to find the error, I put two breakpoints at the lines under "setContentView(..." and debugging, when the cursor reached the last code line "fondo.setBack..." the variable "fondo" was "null" and I think that there is the problem, so when I resume the debugging the app crashes...
I hope you can help me. Thank you!
The problem is that findViewById(R.layout.activity_principal); is going to return null.
You are passing a layout ID (R.layout.activity_principal) instead of a View ID.
It should look something like findViewById(R.id.fondo);.
Let's say I have some strings in Java that I've retrieved from a web script. It doesn't matter really, they're just strings stored in variables.
Now my question is how to dynamically append them to the application (to show the user) and possibly style their position, from Java.
To draw an analogy, I want to do something similar to the following in JavaScript:
var text = document.createElement('div');
text.appendChild(document.createTextNode("some string"));
text.style.position = "whatever";
// etc, more styling
theDiv.appendChild(text); // add this new thing of text I created to the main application for the users to see
I've looked into the TextView, and I don't seem to be using it properly (I don't understand the constructor I guess?). What I want to try right now is to have the user press a button in my application and then have some text dynamically generated. Here's what I've been trying:
search_button = (Button) findViewById (R.id.backSearchButton);
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String test = new String("testing!");
TextView test2 = new TextView(this); //constructor is wrong, this line gives me an error
test2.setText(test);
setContentView(test2);
}
});
As you can probably tell, I don't come from much of a Java background. I'm just trying to draw parallels to stuff I would want to do for a web app.
Thanks for the help.
Try:
TextView test2 = new TextView(ParentActivity.this);
replace "ParentActivity" with the name of your activity.
your this pointer is a reference to the OnClickListener that you have anonymously created. You need a pointer to the containing Activity.
You would probably be better constructing your text view in the onCreate of your activity and just setting the text from your onClick method
I'm new to Java and Android, myself. But I'll give your question a try.
You have to decide if you want to create the TextView in XML or dynamically in Java. I think creating it in XML in the layout creator is better.
I don't think you should be using setContentView(test2).
If you create a TextView dynamically, I don't think you need to put anything in its constructor. But you do have to add the TextView to the parent view. In other words, let's say you have a LinearLayout somewhere in your layout. You have to do: linearLayout1.add(myTextView) or something.
The rest of your code seems fine. But then again, I'm still new to this, myself. Let me know how helpful this answer is, I'll try Googling for more help if it's not enough.