Android webView InAppBrowserFragment error encroachment menu - android

I have can WebView in Fragment, when move tab Fragment,and I touch Button aboutUs--> move in Fragment AboutUs; I repeat about 10times.
Error is same picture.
can everyone help me?. Thank :
Code Fragment load WebView :
public class InAppBrowserFragment
extends BaseFragment {
private static final String LINK_PAGE = "linkPage";
private static final String TITLE_ACTION_BAR = "titleActionBar";
#InjectView(R.id.web_settings)
WebView mWebViewSettings;
#InjectView(R.id.actionbar_settings_sub)
ActionBar mActionBar;
#InjectView(R.id.img__settings_background)
ImageView mImgSettingsBackground;
/**
* Static method used to create an instance for this fragment.
*
* #return New instance of Fragment.
*/
public static InAppBrowserFragment newInstance(String titleActionBar,
String linkPage) {
final InAppBrowserFragment fragment = new InAppBrowserFragment();
final Bundle data = new Bundle();
if (titleActionBar != null) {
data.putString(LINK_PAGE,
linkPage);
data.putString(TITLE_ACTION_BAR,
titleActionBar);
}
// Attach data with fragment.
fragment.setArguments(data);
return fragment;
}
#Override
protected int getLayoutResourceId() {
return R.layout.fragment_in_app_browser;
}
#Override
protected void initUi(final Bundle savedInstanceState) {
String titleActionBar = getArguments().getString(TITLE_ACTION_BAR);
//set background
CommonUtil.displayImage(getActivity(),
CommonUtil.getDrawableResource(R.drawable.img_random_frontpage_1),
this.mImgSettingsBackground,
0,
0,
0,
true,
false,
null);
//set UI Action Bar
this.mActionBar.setupUI(null,
titleActionBar,
R.drawable.ab_ic_back,
0,
"");
this.mActionBar.setButtonRightPadding(0);
this.mActionBar.setButtonLeftListener(new ActionBar.IActionBarButtonLeftListener() {
#Override
public void onButtonLeftClicked(final View view) {
popBack(true);
mWebViewSettings.canGoBack();
}
});
}
#Override
protected void loadData(final Bundle savedInstanceState) {
String linkPage = getArguments().getString(LINK_PAGE);
// Init webview setting
WebSettings settings = mWebViewSettings.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(true);
settings.setSupportZoom(true);
mWebViewSettings.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
});
mWebViewSettings.loadUrl(linkPage);
}
}
Conrect:
Inconrect:

i fix sucess :(set wrap_content for Webview )
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/CreateTrips.Widget.ScreenContent.Fragment">
<ImageView
android:id="#+id/img__settings_background"
style="#style/CreateTrips.Widget.BackgroundImage"
android:contentDescription="#null"/>
<com.createtrips.ui.widgets.ActionBar
android:id="#+id/actionbar_settings_sub"
style="#style/CreateTrips.Widget.ActionBar"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:layout_marginTop="#dimen/widget_action_bar_height"
>
<WebView
android:id="#+id/web_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</FrameLayout>

Related

Android check box tik mark disappear randomly when moving from one fragment to another using android-material-stepper

Instead of getting checkbox like this(i am getting it only few times randomly when moving from on fragment to another).
I am getting like this(checkbox is still true but only tik mark is missing randomly)
I am using onSaveInstanceState and onViewStateRestored. The problem is the checkbox tik mark only disappears and comes back few times but the state of checkbox is still selected i see blue color around all the selected check boxes that selected color doesn't go away only the tik mark goes away and comes back randomly.
Layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_tv"
android:text="TV"
android:theme="#style/CheckBoxTheme"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tv" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
My Fragment:
public class StepFragmentTwo extends Fragment implements BlockingStep {
private static final String CLICKS_KEY = "clicks";
private static final String TAG = "ADERVERTISMENT";
private int i = 0;
FragmentManager fm = getFragmentManager();
CheckBox c;
Boolean tv = false ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(getLayoutResId(), container, false);
c = (CheckBox)v.findViewById(R.id.checkBox);
//initialize your UI
return v;
}
protected int getLayoutResId() {
return getArguments().getInt(String.valueOf(R.layout.step2));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(CLICKS_KEY, i);
super.onSaveInstanceState(outState);
if(outState!=null) {
outState.putBoolean("c", c.isChecked());
}
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState!=null) {
tv = savedInstanceState.getBoolean("c");
}
}
#Override
public void onResume() {
super.onResume();
c.setChecked(tv);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (c.isChecked()) {
tv = true;
}
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putBoolean("tv", tv);
editor.apply(); // This line is IMPORTANT !!!
callback.goToNextStep();
}
}, 200L);
}
#Override
#UiThread
public void onCompleteClicked(final StepperLayout.OnCompleteClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
callback.complete();
}
}, 2000L);
}
public static StepFragmentTwo newInstance(#LayoutRes int layoutResId) {
Bundle args = new Bundle();
args.putInt(String.valueOf(R.layout.step2), layoutResId);
StepFragmentTwo fragment = new StepFragmentTwo();
fragment.setArguments(args);
return fragment;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
public void onBackClicked(StepperLayout.OnBackClickedCallback callback) {
//Toast.makeText(this.getContext(), "Your custom back action. Here you should cancel currently running operations", Toast.LENGTH_SHORT).show();
callback.goToPrevStep();
}
}
In short you can do,
#Override
public void onResume() {
super.onResume();
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
tv = editor.getBoolean("tv", tv);
c.setChecked(tv);
}

Use YoutubePlayerView on fragment section

I found some similar situation, like this and this, but none of then solved my problem.
I have wanna have a screen with youtube video and some text information like this:
I'm using a activity and a fragment, both with base class that extended YouTubeBaseActivity and YouTubePlayerFragment.
But when I'm trying to open the fragment it show a npe but it don't show where. Since I'm getting the layout and view right, I don't now what is going on.
Hope that it don't get downvotes because is a npe question, but is different from usual, this API call don't show me where the NPE happen and I saw the other people has problems like this
Obs: I'm using this extend base concept because more places will have this videos behaviour and I'm trying to avoid code repeat.
Logcat
XML
<android.support.constraint.ConstraintLayout
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".screens.mine.fragments.MineStepsFragment">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/mine_steps_youtube_player"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/background_white"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
</com.google.android.youtube.player.YouTubePlayerView>
</android.support.constraint.ConstraintLayout>
Activity
public class MineAccidentActivity extends BaseYoutubeActivity {
#Override
protected void initializeActionBar() {
actionbarLeftBtn.setVisibility(View.VISIBLE);
actionbarTitle.setVisibility(View.VISIBLE);
}
#Override
protected int getActionbarTitle() {
return R.string.mine_accident;
}
#Override
protected int getContentView() {
return R.layout.mine_accident_activity;
}
#Override
protected void assignViews() {
MineAccidentController.getInstance().attachToActivity(this, R.id.mine_container);
}
#Override
protected void prepareViews() {}
/////////////////// BACK ////////////////////
#Override
public void onBackPressed() {
if (!MineAccidentController.getInstance().isFirstFragmentShown()) {
MineAccidentController.getInstance().showPreviousFragment();
} else {
super.onBackPressed();
}
}
/////////////////// LIFE CYCLE ////////////////////
#Override
protected void onDestroy() {
MineAccidentController.getInstance().onDestroy();
super.onDestroy();
}
}
Fragment Controller
public class MineAccidentController extends BaseYoutubeController {
private String accidentType;
#Override
protected ArrayList<android.app.Fragment> initFragments() {
ArrayList<android.app.Fragment> fragments = new ArrayList<>();
fragments.add(new MineStepsFragment());
return fragments;
}
//create Class
public static MineAccidentController getInstance() {
if (null == instance) {
synchronized (MineAccidentController.class) {
if (null == instance) {
setInstance(new MineAccidentController());
}
}
}
return (MineAccidentController) instance;
}
public String getAccidentType() {
return accidentType;
}
public void setAccidentType(String accidentType) {
this.accidentType = accidentType;
}
}
Fragment
public class MineStepsFragment extends BaseYoutubeFragment {
//Not in Layout
private String videoUrl;
////////////// IMPLEMENT_METHODS //////////////
#Override
protected int getFragmentContentView() {
return R.layout.mine_steps_fragment;
}
#Override
protected int getYoutubePlayerView() {
return R.id.mine_steps_youtube_player;
}
#Override
protected void assignViews() {
}
#Override
protected void prepareViews() {
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if(!wasRestored){
checkType();
youTubePlayer.cueVideo(videoUrl);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
showErrorToast(getActivity(), R.string.error_initialize_video);
}
////////////// FUNCTIONS //////////////
private void checkType() {
if(MineAccidentController.getInstance().getAccidentType().equals(Parameters.ACCIDENT_PERSONAL)){
videoUrl = Properties.MINE_PERSONAL_VIDEO;
}
else {
videoUrl = Properties.MINE_WORK_VIDEO;
}
}
}
Base Fragment
public abstract class BaseYoutubeFragment extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener {
protected View fragmentView = null;
protected YouTubePlayerView youTubePlayerView;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
assignViews();
prepareViews();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
fragmentView = inflater.inflate(getFragmentContentView(), container, false);
youTubePlayerView = fragmentView.findViewById(getYoutubePlayerView());
youTubePlayerView.initialize(com.can_apps.eva_ngo.properties.Properties.API_KEY, this);
return fragmentView;
}
/////////////////// ABSTRACT METHODS ////////////////////
protected abstract int getFragmentContentView(); //Get Layout R.layout.name_file
protected abstract int getYoutubePlayerView(); //Get Container for YOutube Video
protected abstract void assignViews(); //Used for findById the params
protected abstract void prepareViews(); //Used for start the values of params
/////////////////// SHOW MESSAGES ////////////////////
public void showErrorToast(Context context, final int message) {
Toast toast = Toast.makeText(context, getString(message), Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundResource(R.color.background_red_transparent);
toast.show();
}
/////////////////// SNACK BAR ////////////////////
public void showSnackBar(final int text) {
Snackbar.make(Objects.requireNonNull(getView()), getString(text), Snackbar.LENGTH_SHORT).show();
}
public void showSnackBar(final int mainTextStringId, final int actionStringId, View.OnClickListener listener) {
Snackbar.make(Objects.requireNonNull(getView()),
getString(mainTextStringId),
Snackbar.LENGTH_LONG)
.setAction(getString(actionStringId), listener).show();
}
}
Looking at the logcat it looks like your YouTubePlayerView is null when you are calling one of its methods.
The YouTube Player API is quite buggy and difficult to use correctly. To solve this problems (and others) I have built an alternative player Android-YouTube-Player, it's open source and you can do whatever you want with it.
In your case, you won't have to meddle with Fragments and transactions, since my YouTubePlayerView is just a regular view and requires no special Fragments or Activities. You can drop it wherever you want.
Hope it could be useful to you as well!

My ListPreference does not persist values when changing screen orientation

I have been stuck on this for days and tried different workarounds.
When I change screen orientation, the preference summary loses its value.
I have a custom ListPreference which when user clicks, pops up two choices for buddy - myself, and some other (in the actual program, user selects a buddy from Contacts).
I set the summary to the selected buddy's email address.
clicking preference pops up list preference which, depending on what is clicked, shows myself, or contacts picker to select a buddy.
'myself' was selected
flipping phone loses buddy
Here is a working program stripped to show the essentials.
class BuddyPreference2
public class BuddyPreference2 extends ListPreference {
String buddy;
private static final String TAG = "REGU";
public BuddyPreference2(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
persistString((String) buddy);
}
super.onDialogClosed(positiveResult);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.onSetInitialValue(restoreValue, defaultValue);
if (restoreValue) {
// Restore existing state
buddy = this.getPersistedString("none set");
} else {
// Set default state from the XML attribute
buddy = (String) defaultValue;
persistString(buddy);
}
}
/*
* (non-Javadoc)
*
* #see android.preference.ListPreference#setValue(java.lang.String)
*/
#Override
public void setValue(String value) {
String s = new String(value);
super.setValue(s);
}
#Override
protected View onCreateDialogView() {
View view = super.onCreateDialogView();
return view;
}
}
user_prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#+id/pref_screen" >
<com.mypreferences.BuddyPreference2
android:entries="#array/buddy_entry"
android:entryValues="#array/buddy_value"
android:key="buddy_entry"
android:summary="my buddy"
android:title="my buddy" />
</PreferenceScreen>
class EditAlertPreferencesActivity
public class EditAlertPreferencesActivity extends Activity {
static final String BUDDY = "buddy_entry";
static final String TAG = "REGU";
private static final int CONTACT_PICKER_RESULT = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_prefs_fragment);
}
// Fragment that displays the mesg preference
public static class UserPreferenceFragment extends PreferenceFragment {
protected static final String TAG = "REGU";
private OnSharedPreferenceChangeListener mListener;
private Preference buddyPreference;
String myEmailAddress;
String getMyEmailAddress() {
return "Myself" + " <me#my.com>";
}
public void setBuddySummary(String s) {
buddyPreference.setSummary(s);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myEmailAddress = getMyEmailAddress();
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.user_prefs);
buddyPreference = (Preference) getPreferenceManager().findPreference(BUDDY);
buddyPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String buddyChoice = (String) newValue;
if (buddyChoice.equals(getString(R.string.select))) {
Toast.makeText(getActivity(), "pick a contact", Toast.LENGTH_SHORT);
pickContact();
} else {
buddyPreference.setSummary(myEmailAddress);
}
return false;
}
});
// Attach a listener to update summary when msg changes
mListener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(BUDDY)) {
buddyPreference.setSummary(sharedPreferences.getString(BUDDY, "none set"));
} else {
Log.e(TAG, "error; I do not recognize key " + key);
}
}
};
// Get SharedPreferences object managed by the PreferenceManager for
// this Fragment
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
// Register a listener on the SharedPreferences object
prefs.registerOnSharedPreferenceChangeListener(mListener);
// Invoke callback manually to display the msg
mListener.onSharedPreferenceChanged(prefs, BUDDY);
}
/*
* (non-Javadoc)
*
* #see android.preference.PreferenceFragment#onCreateView(android.view.
* LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public void pickContact() {
String buddyEmailAddress = "Some Buddy " + " <buddy#email.com>";
setBuddySummary(buddyEmailAddress);
}
}
}
user_prefs_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.mypreferences.EditAlertPreferencesActivity$UserPreferenceFragment"
android:orientation="vertical"
android:id="#+id/userPreferenceFragment">
</fragment>
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="buddy_entry">
<item>myself</item>
<item>select a contact</item>
</string-array>
<string-array name="buddy_value">
<item>myself</item>
<item>select</item>
</string-array>
</resources>
class PreferencesActivityExample
public class PreferencesActivityExample extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Open a User Preferences Entry Activity
final Button button = (Button) findViewById(R.id.check_pref_button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
PreferencesActivityExample.this,
EditAlertPreferencesActivity.class));
}
});
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="select">select</string>
</resources>
Issue is that the Preference value selected on the dialog is not saved/updated.
You can easily verify this Close the Activity and launch gain. You will still see the default value , noting to do with orientation change.
FIX: You need to return true to update the new value in preference.
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// do all your other stuff here
return true;
}
True to update the state of the Preference with the new value.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListPreference listPreferenceCategory = (ListPreference) findPreference("pref_list_category");
listPreferenceCategory.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String category = (String) newValue;
CharSequence[] listEntries = listPreferenceCategory.getEntries();
int indexValue = listPreferenceCategory.findIndexOfValue(category);
listPreferenceCategory.setSummary(listEntries[indexValue]);
return true;
}
});
}
In xml:
<ListPreference
android:dialogTitle="#string/pref_category"
android:entries="#array/categories"
android:summary="#string/pref_category"
android:entryValues="#array/categories_value"
android:key="pref_list_category"
android:title="#string/pref_category"/>
That is my worked code. Try it !

mono for android get html source code

I want to get html source code in c# (mono for android)
I add webview in my project. webview name is web.
my code:
WebView webView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main); webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetSupportZoom(true);
webView.Settings.BuiltInZoomControls = true;
webView.Settings.LoadWithOverviewMode = true; //Load 100% zoomed out
webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
webView.ScrollbarFadingEnabled = true;
webView.VerticalScrollBarEnabled = true;
webView.HorizontalScrollBarEnabled = true;
webView.SetWebViewClient(new AwesomeWebClient());
webView.SetWebChromeClient(new AwesomeWebChromeClient(this));
webView.LoadUrl(#"http://www.google.com");
}
private class AwesomeWebClient : WebViewClient { }
private class AwesomeWebChromeClient : WebChromeClient
{
private Activity mParentActivity;
private string mTitle;
private string username;
private string password;
private string oldurl="";
public AwesomeWebChromeClient(Activity parentActivity)
{
mParentActivity = parentActivity;
mTitle = parentActivity.Title;
}
public override void OnProgressChanged(WebView view, int newProgress)
{
mParentActivity.Title = string.Format("Loading {0}%", newProgress);
mParentActivity.SetProgress(newProgress * 100);
if (newProgress==100) mParentActivity.Title=mTitle;
}
}
I open www.google.com in webview component and I want to see html source code
I don't believe that there is a way to obtain the HTML from the WebView.
Instead, you should grab the HTML yourself with a WebRequest, e.g. this handy StackOverflow answer.

twitter integration on android app

I would like to integrate Twitter into my Android application so that I can post messages to Twitter.
This is how I do it
First i made a Dialog for the webview
Twitter_Dialog.java
public class Twitter_Dialog extends Dialog
{
static final int BLUE = 0xFF6D84B4;
static final float[] DIMENSIONS_DIFF_LANDSCAPE =
{ 20, 60 };
static final float[] DIMENSIONS_DIFF_PORTRAIT =
{ 40, 60 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
static final String DISPLAY_STRING = "touch";
private String mUrl;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
public Twitter_Dialog(Context context, String url)
{
super(context);
mUrl = url;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
int orientation = getContext().getResources().getConfiguration().orientation;
float[] dimensions = (orientation == Configuration.ORIENTATION_LANDSCAPE) ? DIMENSIONS_DIFF_LANDSCAPE : DIMENSIONS_DIFF_PORTRAIT;
addContentView(mContent, new LinearLayout.LayoutParams(display.getWidth() - ((int) (dimensions[0] * scale + 0.5f)), display.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
}
private void setUpTitle()
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Website");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(BLUE);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView()
{
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new Twitter_Dialog.DialogWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
System.out.println(" mURL = "+mUrl);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class DialogWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
Twitter_Dialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0){
mTitle.setText(title);
if(title.equals("Twitter")){
//This will close the Dialog after tweeting
Twitter_Dialog.this.dismiss();
}
}
mSpinner.dismiss();
}
}
}
//And then into your Main.java
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Twitter_Dialog(Main.this,"http://twitter.com/?status="+Uri.encode("Twitter Post")).show();
}
}
In addition to d.'s solid choices, you could:
Use ACTION_SEND Intents with createChooser(), and if the user has a Twitter application installed (Twidroid) they can use it to update their status
Use an existing Twitter Java API, like JTwitter
Everything you need to know about communicating with Twitter is here.
For sending HTTP requests from your application, check out this guide.
You can use Twitter Helper for integrating Twitter into your Android app. Its very simple.
Try with this simple client TwitterEasyClient
Just add permissions in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And use it in this way:
//setup
TwitterDialogFragment twitterDialog = new TwitterDialogFragment.Builder("message","url.com") //
.callbackUrl("http://www.website.com") //
.consumerKey("XXXXXXXXXXXXXXXXXXXXXX") //
.consumerSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") //
.urlOAuth("oauth_verifier") //
.build();
//show the dialog
twitterDialog.show(getSupportFragmentManager(), TwitterDialogFragment.class.getSimpleName());
Always go for the latest technologies as twitter integration can be done easily using Twitter4j, also the APIs provided by twitter does change from time to time. Twiter sdk would a good option. U can find the details for it here for twitter4j.
For some people who want to use twitter4j and DialogFragment also support orientation changing check out my gist
https://gist.github.com/zeroarst/10071064adcf171277f9

Categories

Resources