Android setUserVisibleHint never gets called? - android

I need to know when my fragment is visible, I was using setMenuVisibility but I now know it's not a good option. I'm trying to implement setUserVisibleHint on a FragmentStatePagerAdapter Fragment, however it never gets called.
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class Contacts extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_screen_contacts, container, false);
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d("MyFragment", "This never shows up.");
Toast.makeText(getActivity(), "Neither does this", Toast.LENGTH_LONG).show();
}
}
I'm running API level 19, and set a minimum API Level of 15 on my AndroidManifest. Is there anything else to do to get setUserVisibleHint, what am I doing wrong?

setUserVisibleHint is available so that you have a way to tell the system the fragment is in fact not visible and not the other way around, when you are doing some fancy fragment transactions that specifically hide it. You can't use it to determine visibility and it defaults to true.
You should use the isVisible call to know if the fragment is visible and onAttach of the fragment or the root view classes to get callbacks when it's been attached to the activity or the respective root views.

setUserVisibleHint()
only works in a FragmentPagerAdapter.
Please refer to Is Fragment.setUserVisibleHint() called by the android System?

Related

WebView for secified Area in LibGdx based Android app

I have built an app for crypto currencies, to maintain a portfolio. I planned to show the latest news items in the same app.
The whole project is an Android app done in LibGdx.
Question
How to have a webview for the area "Part-B"?
LigGdx have anything like WebView?
Does LibGdx has any extensions to take care of WebView?
Screenshot
Starting with your last two questions; no. LibGDX does currently no extensions, nor native support for webviews or something similar. You can, however, create a custom layout. LibGDX has a initializeForView method, which you can use to grab the View itself. This is inflated in a Fragment, which is added to the layout itself. The WebView is then the other view.
First off, the launcher:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gdxwebview);
// Create the fragment
GDXWithWebview fragment = new GDXWithWebview();
getSupportFragmentManager().beginTransaction().
add(R.id.fragmentRoot, fragment).
commit();
}
#Override
public void exit() {}
}
Since fragments are involved, the launcher is different from the generated launcher
For the fragment:
The reason behind using a fragment is to inflate LibGDX into the fragment, which ends up as a sub-unit of the activity. If you set the content view in the activity, you will not get a WebView in there as well.
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class GDXWithWebview extends AndroidFragmentApplication{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// return the GLSurfaceView on which libgdx is drawing game stuff
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();//Configure with whatever you need
return initializeForView(new MyGdxGame(), config);//WARNING!! Replace MyGdxGame with your game class.
}
}
And finally, the layout. It's a basic layout, and the weights (/sizes) may need tweaking for you to get it to look just like you want it to
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gdxwebview);//The layout; comes later
// Create the fragment
GDXWithWebview fragment = new GDXWithWebview();
getSupportFragmentManager().beginTransaction().
add(R.id.fragmentRoot, fragment).
commit();//Add the fragment
}
#Override
public void exit() {}
}
In addition, if you plan on using the WebView to go online, you need the Internet permission (if you use it to execute JavaScript or other web content locally, without going on the Internet, you shouldn't need it):
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class GDXWithWebview extends AndroidFragmentApplication{
View root;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// return the GLSurfaceView on which libgdx is drawing game stuff
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();//Configure with whatever you need
root = initializeForView(new MyGdxGame(), config);//WARNING!! Replace MyGdxGame with your game class.
//declaredInTheClassWebView = (WebView) root.findViewById(R.id.webView);//For initialization, make sure you call root.findViewById, not findViewById. You have to specify the view in which to find the ID when dealing with Fragments.
return root;
}
}
And per the LibGDX documentation on use with Fragments, you also need the v4 support library. Assuming you use Gradle 4.1 and Android Studio:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragmentRoot"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<WebView android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"/>
</LinearLayout>
If you use an earlier version of Gradle and the Gradle plugin:
<uses-permission android:name="android.permission.INTERNET" />
And if you don't use Gradle, find the appropriate call for your build system. If you don't have a build system, grab the jar manually and add it to the classpath.

onclick event in fragment activity not working

I have a activity A in which I have a fragment.
In this activity Fragment changes to fragment A(default when activity A is called) or fragment B based on user input in activity A.
In both fragments A & B I have a button with on click listener. but this button works only for the first time when activity A is started.
when user changes fragment the button in those fragments stop responding to on click.
Please suggest what I need to do in order to make buttons in fragment A & B work when fragments are changed by user.
I am replacing fragments based on user input by this code:
fr = new FragmentOneDice();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
In fragment activity code is like this for on click listener button.
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Collections;
public class FragmentOneDice extends Fragment implements View.OnClickListener {
Button button1;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_fragment_one, container, false);
button1 = (Button) view.findViewById(R.id.button_one);
button1.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
//MY CODE HERE
}
The problem was in my activity_main.XML, where I had defined <Fragment> as a placeholder for all fragments and had set one fragment as default. So when other fragment was loaded it was getting overlapped resulting in on click event on the button not working, I changed the <Fragment> to <FrameLayout> as a placeholder. And my problem was solved.
First You remember one thing,
fragment to fragment direct transaction,or fragment to fragment direct replacement is not possible. it is possible only throw the Activity.
Define a interface in your first fragment and make container Activity to implement that interface, so you can send your data from Fragment to Activity .In another hand create Second Fragment and define a interface in it. In Content Activity inside implemented methods of First Fragment interface on that define a Second Fragment ,here we assign a data to the second Fragment through interface.

Can not resolve method 'findViewById(int)'

I'm having a trouble with findViewByid but I can't find where the problem is.
Here's my FirstFragment class code:
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.List;
public class FirstFragment extends Fragment {
public static final String TAG = "first";
private WebView mWebView;
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.secondefragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
You need to do this in onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondefragment, container, false);
mWebView = (WebView) view.findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
return view;
}
Fragment doesn't provide thefindViewById() method. This is provided in Activity or View. When implementing a Fragment you don't inflate your views in onCreate() (like you normally do in an Activity.) Instead, you do it in onCreateView() and you need to use the inflated root View to find the ID within the layout you inflated.
getActivity().findViewById() works. However, this isn't a good practice because the fragment may be reused in another activity.
The recommended way for this is to define an interface.
The interface should contain methods by which the fragment needs to communicate with its parent activity.
public interface MyInterfcae {
void showTextView();
}
Then your activity implements that Interface.
public class MyActivity extends Activity implements MyInterfcae {
#Override
public void showTextView(){
findViewById(R.id.textview).setVisibility(View.VISIBLE);
}
}
In that fragment grab a reference to the interface.
MyInterface mif = (MyInterface) getActivity();
Call a method.
mif.showTextView();
This way, the fragment and the activity are fully decoupled and every activity which implements that fragment, is able to attach that fragment to itself.
I had this problem when I downloaded sample project from github. This project had
compileSdkVersion 23
buildToolsVersion "23.0.0"
targetSdkVersion 23
in Activity context and findViewById() were in red color inside onCreate() method. So I updated the above versions to
compileSdkVersion 25
buildToolsVersion "25.0.3"
targetSdkVersion 25
and error got resolved.
I meet the same question in Android studio learning,just because I create the project by Fragment. Choose Blank Activity with no Fragment would solve it.
I found solution by changing targetSdkVersion from 23 to 21
Add getView() before findViewById() method.
Like this:
getView().findViewById(R.id.potatoes);
getActivity().findViewById()
This works it removes the red colour of findviewby id and it doesnt say cannot resolve symbol but when i put a colin in the end the whole statement is underlined and it says unreachable statement.
barChart =(BarChart)getActivity().findViewById(R.id.barchart);
I am also doing this in fragment.
This is how you can solve the problem:
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);

Get rid of fragments

I decided to not use fragments for now, although Android wants developers to now use it.
But I don't find it useful at the beginning. Unfortunately my IDE prepares everything to use fragments, so my question basically is, how to I get rid of everything, thats necessary for fragments? Is there a way to create a project without fragments? Thats what I did:
package com.pthuermer.juraquiz;
import java.io.IOException;
// import com.pthuermer.juraquiz.QuizActivity.PlaceholderFragment; // only necessary for Fragments
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class AppLaunch extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_launch);
/* FRAGMENTS
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
END FRAGMENTS */
// code goes here...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_launch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
* Useredit: not going to use fragments for now.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_launch,
container, false);
return rootView;
}
}
*/
}
I think many people in the Android community will agree that fragments are not easy to handle and even draw new problems, some of them without even a decent proper solution.
Nevertheless, trying to remove all fragments from an app is not an easy task and might require good Android programming skills. You will have to convert your fragments either to views or activities, and that is not so easy to do, especially for activities containing multiple fragments.
The best option so far is to use mortar from Square, but this alternative is not totally ready and mature yet and using it requires, TMHO, advanced Android skills.
So, if I were a relatively new programmer in the Android world, I would keep fragments, get used to them, understand how they can be used to create reusable components and make apps that work on both phones and tablets.
After a while, when you will master them, you will find their drawbacks, and be able to look for alternatives.
I tried to study mortar from Square three times and still I haven't the slightest idea how to use it. So I went ahead and used Kotlin+Anko, switched all Fragments to Views and I'm more than happy - the code base is three times smaller, no dirty Fragment hacks, no NPEs that view has not been created for unknown reason, etc. Just implement views as follows:
class QuestionnaireView(ctx: Context, questions: List<Question>): _LinearLayout {
init {
orientation = LinearLayout.VERTICAL
for (question in questions) {
verticalLayout {
textView {
text = question.title
}.lparams(matchParent, wrapContent)
... etc - generate answer fields as necessary
}.lparams(matchParent, wrapContent)
}
}
}
Advantages:
Pass parameters using constructors like a human being, not via retarded arguments Bundle
No longer worry about the Fragment lifecycle and whether onCreateView() has yet been called or not.
Gets rid of exceptions thrown in Android's moveToState() mammoth method
Get rid of thousands layout.xml files stored in a single directory
Get rid of that styles.xml horrible mess
No need to define multiple layouts just to show a list+details on 720dp devices: just add if(screenWidthDp>=720) { detailView {} } to your init block.
Disadvantages:
No layout previews
Android Studio will become so slow it's almost useless.
You'll need to generate IDs for those views, otherwise their state will be lost on rotate

Blank Fragment in android 2.3.3 (but not 4.3) with ActionBarCompat

package com.example.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new PlaceholderFragment()).commit();
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
When I run this code in a 4.3 emulator I get the desired "Hello world!" message. In the 2.3.3 emulator howerer I get a blank screen (ActionBar does get displayed).
Apparently this is a known bug for Android 2.3 and below. There is a filed bug for this here.
Solution for support library versions prior to v19:
Try creating an XML layout for the Activity (i.e. just a ViewGroup like LinearLayout or RelativeLayout and give it an id). Then call setContentView(R.layout.newLayout) in the Activity's onCreate(). Then use the id of the ViewGroup as the first parameter of FragmentTransaction.add().
This issue has been resolved as of version 19 of the support library. If you update to the latest version of the support library using the SDK manager your code should work.
You might also find post #6 on the link above helpful.

Categories

Resources