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);
Related
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.
I have been working on iOS for a while and implemented the following code where it shows WebView in the View.
UIView contentView = new UIView();
UIWebView webView = new UIWebView(contentView.Frame);
I wonder how the above code could be written in the Android. I have written the following but getting error. I am newbie to the Android.
View contentView = new View();
WebView webView = new WebView(contentView.LayoutParamaters);
I think this is a misunderstanding of the differences between iOS and Android and how Xamarin supports cross platform C#. The APIs between the 2 platforms are very different, while UIView is conceptually similar to View in reality they map to different APIs. UIView is an iOS specific api and View is an Android specific API, they are each a thin layer on top of the corresponding native controls and have nothing to do with each other.
I'd suggest working through some of the Xamarin.Android tutorials to get an idea of the differences between Android and iOS.
Regarding the errors:
The constructor for View needs a Context provided through to the constructor. You can do this in 2 ways, provide the owning activity or the global application context:
// In the scope of an Activity.
View contentView = new View(this); // "this" is the activity reference.
// In another scope...
View contentView = new View(Android.App.Application.Context);
For your 2nd error, WebView does not have a constructor that takes that parameter.
Fix it by providing nothing:
WebView webView = new WebView();
Here's a minimal example of how to show a WebView. The layout XML for your Activity would be something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="#+id/yourWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout
And the code of your Activity would just be this...
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebViewActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
webView = (WebView) findViewById(R.id.yourWebView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com/");
}
}
Or if you wanted to add the WebView programmatically, your Activity code would look something like this...
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
public class WebViewActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
RelativeLayout parent = (RelativeLayout) findViewById(R.id.containerView);
webView = new WebView(this);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com/");
parent.addView(webView, 0);
}
}
AppIntro is an Android Library that helps you make a cool intro for your app.
AppIntro Library
// Add your slide's fragments here
// AppIntro will automatically generate the dots indicator and buttons.
addSlide(first_fragment);
addSlide(second_fragment);
addSlide(third_fragment);
addSlide(fourth_fragment);
But when I try to attach a fragment created by me, I get an error.
And this is the error:
How can i do to add my fragment1?
While addSlide() method needs android.supportv4.app.Fragment as parameter, so your custom Fragment1 should extend from android.supportv4.app.Fragment class.
1、
import android.support.v4.app.Fragment;
2、
public class Slide_First extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.slide_first, null);
return view;
}
}
first: create your fragments like always and add the xml elements you need to it, and in your activity just do this
Edit: It is not necessary to extend to AppIntro or AppIntro2
public class MyIntro extends AppIntro2 implements ISlidePolicy {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
Intro1 fragment1 = new Intro1 ();
Intro2 fragment2 = new Intro2 ();
Intro3 fragment3 = new Intro3 ();
addSlide (fragment1);
addSlide (fragment2);
addSlide (fragment3);
//Only personalization
showStatusBar (false);
showSkipButton (false);
setFadeAnimation ();
setBarColor (Color.TRANSPARENT);
}
}
Edit2: import these dependences in your fragment
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
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?
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.