popupwindow not working with setContentView - android

Solution
Thanks to a clue in codeMagic's answer, the solution to the problem was to set the width and height using the setWidth() and setHeight() methods
Question
I am trying to display a PopupWindow in Android using the following code but it doesn't seem to be working
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow test = new PopupWindow();
test.setContentView(inflater.inflate(R.layout.test, null, false));
test.showAtLocation(findViewById(R.id.main_container), Gravity.CENTER, 0, 0);
}
....
}
Can you tell me where I am going wrong?
EDIT:
What I expect a popup windows to show contain my layout in R.id.test but when i execute the code above, nothing happens. No error or whatsoever
EDIT2:
Added some context to the original code

I decided to use a PopupWindow for what I'm working on now. Mine is in a ListView so it may be a little different but I had to change a couple things to see it. Here are a few things I would suggest to look at because I don't see anything obviously wrong with your code.
Inflate your View first and make sure it doesn't return null
Use a different constructor ( I used new PopupWindow(holder.textNotes, 500, 500, true);
- Replace holder.textNotes with your inflated View and the sizes with something suitable for the screen you are working on.
Note I used this constructor so I could make it focusable for an EditText
3 .I gave my View a background color so I could make sure it was showing
There are several different constructors you can use when creating an instance of PopupWindow which you can find here in the Docs. The one I have used above allows you to set the height and width of the window. This prevents the need for the calls, setHeight() and setWidth() as pointed out by vidhu in the comments.

You should call method update
to display your popup

Related

How to solve this error Attempt to invoke virtual method 'void android.widget.VideoView.setVideoURI(android.net.Uri)' [duplicate]

First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)
Most of them come with the advice to use android:id instead of just id in the XML file. I did.
From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.
In my location_layout.xml, I use:
<FrameLayout .... >
<some.package.MyCustomView ... />
<LinearLayout ... >
<TextView ...
android:id="#+id/txtLat" />
...
</LinearLayout>
</FrameLayout>
In my Activity I do:
...
setContentView( R.layout.location_layout );
and in my custom view class:
...
TextView tv = (TextView) findViewById( R.id.txtLat );
which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:
...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );
which also returned null.
Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.
So what the heck am I doing wrong?
I'll appreciate any comments.
which returns null
Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.
Possibly, you are calling findViewById before calling setContentView?
If that's the case, try calling findViewById AFTER calling setContentView
Make sure you don't have multiple versions of your layout for different screen densities. I ran into this problem once when adding a new id to an existing layout but forgot to update the hdpi version. If you forget to update all versions of the layout file it will work for some screen densities but not others.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
This would be wrong
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context);
}
This is correct
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context,attrs);
}
Alongside the classic causes, mentioned elsewhere:
Make sure you've called setContentView() before findViewById()
Make sure that the id you want is in the view or layout you've given to setContentView()
Make sure that the id isn't accidentally duplicated in different layouts
There is one I have found for custom views in standard layouts, which goes against the documentation:
In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id attribute works for all the views in the layout except the custom ones. The solution I use is:
Replace each custom view with a FrameLayout with the same layout properties as you would like the custom view to have. Give it an appropriate id, say frame_for_custom_view.
In onCreate:
setContentView(R.layout.my_layout);
FrameView fv = findViewById(R.id.frame_for_custom_layout);
MyCustomView cv = new MyCustomView(context);
fv.addView(cv);
which puts the custom view in the frame.
In my case, I had 2 activites in my project, main.xml and main2.xml. From the beginning, main2 was a copy of main, and everything worked well, until I added new TextView to main2, so the R.id.textview1 became available for the rest of app. Then I tried to fetch it by standard calling:
TextView tv = (TextView) findViewById( R.id.textview1 );
and it was always null. It turned out, that in onCreate constructor I was instantiating not main2, but the other one. I had:
setContentView(R.layout.main);
instead of
setContentView(R.layout.main2);
I noticed this after I arrived here, on the site.
#Override
protected void onStart() {
// use findViewById() here instead of in onCreate()
}
A answer for those using ExpandableListView and run into this question based on it's title.
I had this error attempting to work with TextViews in my child and group views as part of an ExpandableListView implementation.
You can use something like the following in your implementations of the getChildView() and getGroupView() methods.
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout, null);
}
I found this here.
FWIW, I don't see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is,
findViewById()
after
setContentView().
The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:
<include layout="#layout/content_main" />
When I added that to activity_main.xml, no more NullPointer.
I'm pretty new to Android/Eclipse, by mistake I added the UI stuff to activity_main.xml instead of fragment_main.xml. Took me some hours to figure that out...
I had this same problem. I was using a third-party library that allows you to override their adapter for a GridView and to specify your own layout for each GridView cell.
I finally realized what was happening. Eclipse was still using the library's layout xml file for each cell in the GridView, even though it gave no indication of this. In my custom adapter, it indicated that it was using the xml resource from my own project even though at runtime, it wasn't.
So what I did was to make sure my custom xml layouts and ids were different from those still sitting in the library, cleaned the project and then it started reading the correct custom layouts that were in my project.
In short, be careful if you're overriding a third-party library's adapter and specifying your own layout xml for the adapter to use. If your layout inside your project has the same file name as that in the library, you might encounter a really difficult-to-find bug!
In my particular case, I was trying to add a footer to a ListView. The following call in onCreate() was returning null.
TextView footerView = (TextView) placesListView.findViewById(R.id.footer);
Changing this to inflate the footer view instead of finding it by ID solved this issue.
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
Just wanted to throw my specific case in here. Might help someone down the line.
I was using the directive in my Android UI XML like this:
Parent view:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:visibility="gone" />
Child view (retry_button):
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/retry"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
.findViewById(R.id.retry) would always return null. But, if I moved the ID from the child view into the include tag, it started working.
Fixed parent:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:id="#+id/retry"
android:visibility="gone" />
Fixed child:
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
In my case, I was using ExpandableListView and I had set android:transcriptMode="normal". This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.
For me I had two xml layouts for the same activity - one in portrait mode and one in landscape. Of course I had changed the id of an object in the landscape xml but had forgotten to make the same change in the portrait version. Make sure if you change one you do the same to the other xml or you will not get an error until you run/debug it and it can't find the id you didn't change. Oh dumb mistakes, why must you punish me so?
Set the activity content from a layout resource.
ie.,setContentView(R.layout.basicXml);
In addition of the above solutions you make sure the
tools:context=".TakeMultipleImages"
in the layout is same value in the mainfest.xml file :
android:name=".TakeMultipleImages" for the same activity element.
it is occur when use copy and paste to create new activity
I have the same problem, but I think its worth sharing with you guys.
If you have to findViewById in custom layout, for example:
public class MiniPlayerControllBar extends LinearLayout {
//code
}
you cannot get the view in constructor.
You should call findViewById after view has inflated.
Their is a method you can override onFinishInflate
My case is none like above, no solutions worked. I assume my view was too deep into layout hierarchy. I moved it one level up and it was not null anymore.
INFLATE THE LAYOUT !! (which contains the id)
In my case findViewById() returned null, because the layout in which the element was written, was not inflated...
Eg.
fragment_layout.xml
<ListView
android:id="#+id/listview">
findViewById(R.id.listview) returned null, because I had not done
inflater.inflate(R.layout.fragment_layout, ..., ...);
before it.
Hope this answer helps some of y'all.
In my case I had inflated the layout but the child views were returning null. Originally I had this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) findViewById(R.id.pbListviewFooter);
tvText = (TextView) findViewById(R.id.tvListviewFooter);
...
}
However, when I changed it to the following it worked:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) footerView.findViewById(R.id.pbListviewFooter);
tvText = (TextView) footerView.findViewById(R.id.tvListviewFooter);
...
}
The key was to specifically reference the already inflated layout in order to get the child views. That is, to add footerView:
footerView.findViewById...
It crashed for me because one of fields in my activity id was matching with id in an other activity. I fixed it by giving a unique id.
In my loginActivity.xml password field id was "password". In my registration activity I just fixed it by giving id r_password, then it returned not null object:
password = (EditText)findViewById(R.id.r_password);
In my experience, it seems that this can also happen when your code is called after OnDestroyView (when the fragment is on the back stack.) If you are updating the UI on input from a BroadCastReceiver, you ought to check if this is the case.
findViewById also can return null if you're inside a Fragment. As described here: findViewById in Fragment
You should call getView() to return the top level View inside a Fragment. Then you can find the layout items (buttons, textviews, etc)
In my case, findViewById returned null when I moved the call from a parent object into an adapter object instantiated by the parent. After trying tricks listed here without success, I moved the findViewById back into the parent object and passed the result as a parameter during instantiation of the adapter object.
For example, I did this in parent object:
Spinner hdSpinner = (Spinner)view.findViewById(R.id.accountsSpinner);
Then I passed the hdSpinner as a parameter during creation of the adapter object:
mTransactionAdapter = new TransactionAdapter(getActivity(),
R.layout.transactions_list_item, null, from, to, 0, hdSpinner);
I was facing a similar problem when I was trying to do a custom view for a ListView.
I solved it simply by doing this:
public View getView(int i, View view, ViewGroup viewGroup) {
// Gets the inflater
LayoutInflater inflater = LayoutInflater.from(this.contexto);
// Inflates the layout
ConstraintLayout cl2 = (ConstraintLayout)
inflater.inflate(R.layout.custom_list_view, viewGroup, false);
//Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated.
TextView tv1 = (TextView)cl2.findViewById(cl2);
Ways to debug and find the issue:
Comment out all findViewById in your activity.
Comment out everything except onCreate and setContentView
Run the project and see if any layout is set
In my case, I was using activity_main.xml in both my app module and also my library module. So when I performed the above steps, instead of the layout which I designed in the library, the layout inside app module was inflated.
So I changed the activity_main.xml file name to activity_main_lib.xml.
So make sure you do not have any duplicate layout names in your whole project.
The issue for me was that I had two layouts with the same file name activity_main.xml. (The layouts were in different libraries but in the same app) The issue was solved by renaming one of them to a unique name.
For me it returned null because the given control was (programmatically) hidden. When I put a condition to call findViewByID(id) only when the control is visible, it started working again.
For me it was only null when using Evaluate Expression or the Debug Watch View of the IDE.

Android - onGlobalLayout is not called by ViewTreeObserver

I have a headache in current Android project. I want to detect the changing of the current page. For example, there is a TextView to display device time, which is updated per second. How to detect this change? I searched a lot on SO (thanks SO), but none works for me.
More information: I don't use standard Activity to create page. My way is:
All widgets are created into a View object which is then used to create a container object. After that, I just handle this container to draw on a canvas with a VSYNC callback Choreographer.FrameCallback periodically.
Indeed, it works to draw. All are ok. Except: I want to draw canvas only when the page's content changed. So back to my beginning question, how to detect this "changing" event? I am sure there is some kind of callback to handle this problem. I used the following solution, but onGlobalLayout is not called when textview's text changed.
CanvasAppViewContainer container;//CanvasAppViewContainer extends AbsoluteLayout
LayoutInflater li =(LayoutInflater)getService().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(resourceId, null);//passed a correct the layout id
container = new CanvasAppViewContainer(getService(), view, getWidth(), getHeight(), getSurface());
rootView = (LinearLayout) findViewById(R.id.rootView); //root element of layout
rootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#Override
public void onGlobalLayout() {
Log.d("test", "onGlobalLayout");
}
});
BTW: Even if I register the view tree observer for the textview, onGlobalLayout is still not called.
Thanks
onGlobalLayout() is only called when the layout changes. When you want to detect a change in the text use TextView.addTextChangedListener()

Adding Custom ImageButton to layout in Android causes error

I will start by saying this, while I have some Java training, is my first foray into development for Android.
What I have done is created a custom ImageButton called MapCell that is basically an ImageButton that holds a few extra pieces of information, and it compiles fine.
My problem comes when I want to procedurally create a MapCell in the relevant Activity and add it to my TableLayout which is defined in the xml and has the id 'mapTable'. The relevant bit looks like this:
Random randy = new Random();
MapCell n = new MapCell(randy.nextInt(4), this); //the random number is part of my extra info
findViewById(R.id.mapTable).addView((View)n, 20, 20); //add cell to display
I get one error out of that:
The method addView(View, int, int) is undefined for the type View
Which to me sounds like utter nonsense. I put that View cast in there as desperation after I got this same error with n sitting by itself and nothing changed (Obviously my MapCell is already a View since it extends ImageButton).
I hope a new pair of eyes can tell me what this is about, since I've checked for similar problems and I didn't find any quite like this. Let me now if you need to see more code.
The method findViewById returns a View and the View class doesn't have the method addView(this method is implemented in the ViewGroup and its subclasses). Instead you should write:
((TableLayout)findViewById(R.id.mapTable)).addView(n, 20, 20);
I've cast the return of the findViewById method in a class that actually has the addView method.
You got this problem because method findViewById(R.id.mapTable) returns View object.
In android you can't add one View to another.
You can use addView function with ViewGroup, and all LinearLayout (etc.) objects.

How to add Layout as a child

In my application I have 2 layouts. One's is root layout that changes dynamically and the second is just a form that opens many times. The form must be child of the root layout but I'm failing to perform so.
I assume that I should simply use:
main.AddView(formLayout)
but I can't figure out how get this formLayout object.
Will thank you for possible answers.
Sounds like you need the LayoutInflater object Android reference.
This allows you to create an object from the xml layout in your project.
With the advice of cjk I wrote piece of code that actually answers my question:
setContentView(R.layout.main);
main = ((ViewGroup)findViewById(android.R.id.content));
LayoutInflater inflater = this.getLayoutInflater();
ViewGroup form= (ViewGroup) inflater.inflate(R.layout.formLayout, null);
main.addView(form);
Thank you all
Not sure if I understand the question properly, but something like that might work:
View myView;
myView = (View) this.findViewById(R.id.formLayout);
main.addView(myView);
By get I figure you mean you want to retrieve a field in the new opened layout, you can do it by making it a new Intent and using startActivityForResult instead of startActivity.

findViewByID(R.layout.skeleton_activity) returns null

I am trying to register a context menu in a skeleton app's OnCreate():
/** Called with the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.skeleton_activity);
View v = findViewById(R.layout.skeleton_activity);
registerForContextMenu(v);
// Find the text editor view inside the layout, because we
// want to do various programmatic things with it.
mEditor = (EditText) findViewById(R.id.editor);
// Hook up button presses to the appropriate event handler.
((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
((Button) findViewById(R.id.clear)).setOnClickListener(mClearListener);
mEditor.setText(getText(R.string.main_label));
}
The debugger tells me that findViewById(R.layout.skeleton_activity) returns null.
#CommonsWare solution to a similar post is to Wait until onFinishInflate(). However, in the sample project he provides, it doesn't seem that he waits until onFinishInflate.
My questions:
Can registerForContextMenu() wait
until onFinishInflate()?
If so, how do I do so?
This line is not correct its asking for id and you are providing layout
View v = findViewById(R.layout.skeleton_activity);
Instead if you want to have object of your root layout element then provide it some id and then try something like this
View v = findViewById(R.id.root_element);
I think you should use
View v = findViewById(R.id.skeleton_activity);
instead.
For the 2nd question, sorry, I 've no idea. Hope to see someone else's answer.
You shouldn't need to wait for the content to inflate in an Activity.
One problem is that findViewById takes an ID (R.id....) when you provide it with a layout (R.layout...). Can you try the following instead, to reference the Activity's root view?
setContentView(R.layout.skeleton_activity);
View content = findViewById(android.R.id.content);
registerForContextMenu(content);
i think the code you have shown is very confusing. Here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-contextmenu-submenu/. In my case it works, i hope you can solve your problem.

Categories

Resources