I have 2 buttons in different fragment1 and another webview in fragment 2. I want to open 2 different websites in the webview whenever I click on the buttons. Please suggest
Please try this -
public class MainHomeActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_first, btn_second;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_home);
btn_first= (Button)findViewById(R.id.btn_first);
btn_second= (Button)findViewById(R.id.btn_second);
btn_second.setOnClickListener(this);
btn_first.setOnClickListener(this);
}
private void loadFragment(String url) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle b = new Bundle();
b.putString("url", url);
webViewFragment.setArguments(b);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_layout, webViewFragment);
fragmentTransaction.commit();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_first:
loadFragment("http://www.google.com");
break;
case R.id.btn_second:
loadFragment("http://www.apple.com");
break;
}
}
}
/activity_main_home.xml/
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/topPanel"
android:orientation="horizontal">
<Button
android:id="#+id/btn_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first"/>
<Button
android:id="#+id/btn_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second"/>
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_layout"
android:layout_below="#+id/topPanel"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
//WebViewFragment.java
public class WebViewFragment extends Fragment {
private View view;
private WebView webview;
ProgressBar webViewPbar;
private String url ;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
url = bundle.getString("url");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main, container, false);
initUI();
return view;
}
private void initUI() {
webViewPbar = (ProgressBar) view.findViewById(R.id.webViewPbar);
webview = (WebView) view.findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
webViewPbar.setProgress(newProgress);
if (newProgress == 100) {
webViewPbar.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (webViewPbar != null) {
webViewPbar.setVisibility(View.GONE);
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (webViewPbar != null) {
webViewPbar.setVisibility(View.GONE);
}
}
});
// webview.loadUrl("http://www.google.com");
webview.loadUrl(url);
}
}
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar
android:id="#+id/webViewPbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
style="#android:style/Widget.Holo.Light.ProgressBar.Horizontal" />
<WebView android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
/androidmanifest file/
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shajib.capturemirror">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name=".MainHomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I'm trying to add a simple fragment and it works perfectly when I use it, until I switch rotations than it crashes.
Here is my code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
//region Fragment
if(savedInstanceState==null){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment_Titlebar fragment = new Fragment_Titlebar();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
Fragment_Titlebar header = (Fragment_Titlebar) getFragmentManager().findFragmentById(R.id.fragment);
header.initFragment(R.string.SignUp, 0, true, true);}
//endregion
voornaam = (EditText)findViewById(R.id.first_name_text);
achternaam = (EditText)findViewById(R.id.last_name_text);
profile = (CircleImageView)findViewById(R.id.profile_image);
try {
//Getting the google account
Intent intent = getIntent();
if (intent.getExtras().get("User") instanceof GoogleSignInAccount) {
GoogleSignInAccount acct = (GoogleSignInAccount) intent.getExtras().get("User");
voornaam.setText(acct.getGivenName());
achternaam.setText(acct.getFamilyName());
if (acct.getPhotoUrl() != null) {
Picasso.with(this).load(acct.getPhotoUrl()).into(profile);
}
}
}
catch (NullPointerException e)
{
}
}}
And the Fragment:
private TextView headerText;
private ImageButton backButton;
private ImageButton homeButton;
private Toolbar background;
public Fragment_Titlebar(){}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_title_bar, container, false);
backButton = (ImageButton) view.findViewById(R.id.backButton);
backButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goBack(v);
}
});
homeButton = (ImageButton) view.findViewById(R.id.homeButton);
homeButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goHome(v);
}
}
);
headerText = (TextView) view.findViewById(R.id.headerText);
background = (Toolbar) view.findViewById(R.id.background);
return view;
}
finally the error message:
FATAL EXCEPTION: main
Process: rickvanfessem.carcoolandroid, PID: 18652
java.lang.RuntimeException: Unable to start activity ComponentInfo{rickvanfessem.carcoolandroid/rickvanfessem.carcoolandroid.AddUser}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
I already tried to do this setRetainInstance(true) but that didn't work.
Please Help
EDIT AFTER REQUEST FOR XML
XML of the Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:android="http://schemas.android.com/apk/res/android">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:background="#color/HeaderRed"
app:theme="#style/AppTheme"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/backButton"
style="#style/image_style"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_arrow_back"
/>
<TextView
android:id="#+id/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
style="#style/HeaderText"
tools:text="Test scherm"/>
<ImageButton
android:id="#+id/homeButton"
style="#style/image_style"
android:layout_alignParentRight="true"
android:src="#drawable/ic_home"
/>
</RelativeLayout>
</Toolbar>
</LinearLayout>
try this
Edit your Manifest
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
/>
and in MainActivity
add this Override Method
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation== Configuration.ORIENTATION_PORTRAIT)
{
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
}
}
I'm new at android developing, so asking you for help.
I have the code like that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:id="#+id/progressBar" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</LinearLayout>
In my logic, AdBlock should display at the bottom of view. But in my case it's just not appearing at all. If I past Ad's markup inside LinearLayout it gives me crash of VM.
What I'm doing wrong? Thank you in advance
UPD: Java activity
public class PddViewActivity extends ActionBarActivity{
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdd_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
String file = getIntent().getStringExtra("file");
webView = (WebView) findViewById(R.id.webview);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("PROGRESS IS :", newProgress+"");
progressBar.setProgress(newProgress);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.getVisibility() == WebView.VISIBLE) {
progressBar.setVisibility(WebView.GONE);
}
}
});
webView.loadUrl(String.format("file:///android_asset/html/%s", file));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Your problem is that home_layout has a layoutHeight of match_parent, which means it will consume all the height of its parent leaving none for you adView.
Instead use wrap_content and specify android:layoutWeight="1" to tell it to consume all unused space. Eg
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:id="#+id/progressBar" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</LinearLayout>
Note also:
layout_above has no meaning except within a relative_layout.
fill_parent has been deprecated, use match_parent instead.
You had the same problem with your WebView.
Try with that in your PddViewActivity.java :
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdd_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//instaciate AdView
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
String file = getIntent().getStringExtra("file");
webView = (WebView) findViewById(R.id.webview);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("PROGRESS IS :", newProgress+"");
progressBar.setProgress(newProgress);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.getVisibility() == WebView.VISIBLE) {
progressBar.setVisibility(WebView.GONE);
}
}
});
webView.loadUrl(String.format("file:///android_asset/html/%s", file));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am trying to get a progress bar which shows until the web page is loaded. and if user has no internet connection than a text or toast is showed... but i am unable to get it worked.. searched the whole website. i think its easy to add progress bar to class that expends Activity...
here is my class and layout
package com.nirav.rpta.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.nirav.rpta.R;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
WebSettings webSettings = heroespage.getSettings();
webSettings.setJavaScriptEnabled(true);
heroespage.loadUrl("http://google.co.in/");
return rootView;
}}
and my layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/></RelativeLayout>
Add a ProgressBar to your layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminate="true"/>
</RelativeLayout>
Now in the code:
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
ProgressBar loading = (ProgressBar) rootView.findViewById(R.id.progress);
heroespage.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
loading.setVisibility(View.GONE);
heroespage.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Show error toast
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// Show error toast
}
});
heroespage.loadUrl("http://google.co.in/");
Please check below code for the thing you want.
Your layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<ProgressBar
android:id="#+id/progressBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Your Java file should be like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
// Resources
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar2);
WebSettings settings = heroespage.getSettings();
settings.setJavaScriptEnabled(true);
heroespage.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
// Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Log.e(TAG, "Error: " + description);
Toast.makeText(WebViewScreen.this, "You are offline.",
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
}
});
heroespage.loadUrl(URL);
return rootView;
}}
You must update your layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/progbar"/>
</RelativeLayout>
And then find id of progressbar ProgressBar prog = view.findViewById(R.id.progbar);
to check internet connection use this method
public boolean isConnectingToInternet( Context _context){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
add this code in your oncreateview
heroespage.setWebViewClient(new WebViewCLient(){
public void onPageLoadFinished(){
progbar.setvisibility(View.Gone);
});
if(isconnectingInternet(getActivity()){
heroespage.loadUrl("http://google.co.in/");
}else{
// show your toast here
}
to hide / show progress bar you can use setWebViewClient which provide onPage strated and onPageFinished method
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Show Progress bar
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// hide Progress bar
}
});
To check no internet connection , you can use below code
public static boolean isNetConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
}
return false;
}
Use above method before loading url
if(isNetConnected()) {
heroespage.loadUrl("http://google.co.in/");
} else {
Toast.makeText(getActivity() ,"No internet connection",Toast.LENGTH_SHORT).show();
}
In an RSS fragment I have, the following code that I believe dictates what happens when an item in the RSS list view is created. When an item is clicked it is opened in chrome.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
I would like the link to be opened in a webview activity that I have already created, which currently only loads one webpage, google. This is the webview activity code:
public class WebViewActivity extends ActionBarActivity {
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
web = (WebView) findViewById(R.id.webview);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("https://www.google.com");
web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
web.getSettings().setLoadWithOverviewMode(true);
web.getSettings().setUseWideViewPort(true);
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, MainActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}
#Override
public void onBackPressed() {
startActivity(new Intent().setClass(WebViewActivity.this, MainActivity.class).setData(getIntent().getData()));
return;
}
}
The XML layout for:
Rss Fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="yanay.end.TwitterFragment"
android:background="#color/white"
android:paddingLeft="3dp"
android:paddingRight="3dp">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:paddingRight="0dp"
android:paddingLeft="0dp"
android:paddingTop="0dp"
android:paddingBottom="1dp"
android:layout_height="fill_parent"
android:divider="#color/blue1"
android:dividerHeight="3dp"
>
</ListView>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
</FrameLayout>
And the Web view layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
/>
</RelativeLayout>
EDIT: Now clicking the link opens the web activity, but I still cannot figure out how to set the url to the clicked items url.
place the below code in the onItemClick of RSSFragment
String urlval = uri + "";
Intent mIntent = new Intent(getActivity(), WebViewActivity.class);
mIntent.putExtra(WebViewActivity.URL_KEY, urlval);
startActivity(mIntent);
below code in the WebViewAcitivity
Bundle extras = getIntent().getExtras();
String url = extras.getString(URL_KEY);
web.loadUrl(url);
it should work. I have tried the same.
I am new at android app development.I have a problem with my app.I am doing a simple 'Todo List App'. When I deploy my app to android phone.First time it works well.When I change orientation of device, onCreateView() and onActivityCreated() in MyAddFragment works multiple.And 'Add Button' doesn't work after changing orientation.****Please help me how to get rid of the problem.
The following my activity and fragment classes and xml files.
public class MainActivity extends Activity implements Communicator{
FragmentManager man;
private ArrayAdapter<String> todoArrayAdapter;
private ArrayList<String> todoItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
man = getFragmentManager();
MyAddFragment f1 = new MyAddFragment();
MyListFragment f2 = new MyListFragment();
FragmentTransaction transaction = man.beginTransaction();
transaction.add(R.id.frameLayout1, f1, "Add");
transaction.add(R.id.frameLayout2, f2,"List");
Log.i("a", "onCreate - ADDED FRAGMENT");
if (savedInstanceState == null) {
todoItems = new ArrayList<String>();
}else {
todoItems = savedInstanceState.getStringArrayList("veri");
}
todoArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);
f2.setListAdapter(todoArrayAdapter);
transaction.commit();
}
public void respond(String data) {
MyListFragment fb = (MyListFragment) man.findFragmentById(R.id.frameLayout2);
todoItems.add(data);
todoArrayAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("veri", todoItems);
}
}
public class MyAddFragment extends Fragment{
Button btnAdd;
EditText txtEdit;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
txtEdit = (EditText) getActivity().findViewById(R.id.txtEdit);
comm = (Communicator) getActivity();
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String newRecord = txtEdit.getText().toString();
comm.respond(newRecord);
txtEdit.setText("");
}
});
}
}
public class MyListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container,false);
return view;
}
}
public interface Communicator {
public void respond(String data);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ceng389hw1.MainActivity" >
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:background="#ab3e0f" >
</FrameLayout>
<FrameLayout
android:id="#+id/frameLayout2"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/frameLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#ab3eab"
>
</FrameLayout>
</RelativeLayout>
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab3e0f">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/btnStringAdd" />
<EditText
android:id="#+id/txtEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btnAdd"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btnAdd"
android:ems="10"
android:inputType="text" />
</RelativeLayout>
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab5810" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You should change two files in your Application.
First step, you should add following code in androidmanifest file.
android:configChanges="orientation|screenSize"
After you add the code to Androidmanifest, Your androidmanifes file must be like below.
<activity
android:name="com.example.ceng389hw1.MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name" >
Secon Step, You must be override onConfigurationChanged function like below.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText( this, "landscape", Toast.LENGTH_SHORT ).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
For more detail -> http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
In your main activity check is fragment already added in activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(getFragmentManager().getFragment("Add")==null) {
//initialize fragment, create transaction and commit
}
...
}
You can add configChanges parametre inside manifest.xml it will provide you to ignore reinilizating after config changes you can do it simply like that
<activity
android:name="com.youractivity"
android:configChanges="orientation" />
I hope it will help you :)