I'm trying to add multiple links in a textview similar to what Google & Flipboard has done below with their Terms and conditions AND Privacy Policy shown in the screen shot below:
So far I've stumbled on using this approach
textView.setText(Html.fromHtml(myHtml);
textView.setMovementMethod(LinkMovementMethod.getInstance());
where myHtml is a href.
But it doesn't give me control I need e.g to launch a fragment etc.
Any idea how they achieve this in the two examples below?
I think that I'm a little late to share this, but I have achieved the same using SpannableStringBuilder.
Simply initialize the TextView that you want to add 2 or more listeners and then pass that to the following method that I have created:
private void customTextView(TextView view) {
SpannableStringBuilder spanTxt = new SpannableStringBuilder(
"I agree to the ");
spanTxt.append("Term of services");
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Terms of services Clicked",
Toast.LENGTH_SHORT).show();
}
}, spanTxt.length() - "Term of services".length(), spanTxt.length(), 0);
spanTxt.append(" and");
spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK), 32, spanTxt.length(), 0);
spanTxt.append(" Privacy Policy");
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Privacy Policy Clicked",
Toast.LENGTH_SHORT).show();
}
}, spanTxt.length() - " Privacy Policy".length(), spanTxt.length(), 0);
view.setMovementMethod(LinkMovementMethod.getInstance());
view.setText(spanTxt, BufferType.SPANNABLE);
}
And in your XML, use android:textColorLink to add custom link color of your choice. Like this:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColorLink="#C36241" /> //#C36241 - Rust
And this looks like this:
You can use Linkify (android.text.Spannable,java.util.regex.Pattern,java.lang.String)
String termsAndConditions = getResources().getString(R.string.terms_and_conditions);
String privacyPolicy = getResources().getString(R.string.privacy_policy);
legalDescription.setText(
String.format(
getResources().getString(R.string.message),
termsAndConditions,
privacyPolicy)
);
legalDescription.setMovementMethod(LinkMovementMethod.getInstance());
Pattern termsAndConditionsMatcher = Pattern.compile(termsAndConditions);
Linkify.addLinks(legalDescription, termsAndConditionsMatcher, "terms:");
Pattern privacyPolicyMatcher = Pattern.compile(privacyPolicy);
Linkify.addLinks(legalDescription, privacyPolicyMatcher, "privacy:");
and then you can use the scheme to start an activity for example by adding the scheme in the AndroidManifest:
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<data android:scheme="terms" />
<data android:scheme="privacy" />
</intent-filter>
If you want to do a custom action, you can set the intent-filter to your current activity, which will have a singleTop launchmode.
This will cause onNewIntent to be fired where can make your custom actions:
#Override
protected void onNewIntent(final Intent intent) {
...
if (intent.getScheme().equals(..)) {
..
}
}
Here's my solution:
First we need to have clickable links in our TextView:
Here's my TextView in the xml layout, do not add any links handling
parameters.
<TextView
android:id="#+id/sign_up_privacy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/terms_and_privacy"/>
In strings file, I added the resource text with html tags
<string name="terms_and_privacy">By signing up you agree to our Terms of Service and Privacy Policy.</string>
In onCreateView set LinkMovementMethod to the TextView
TextView privacyTextView = (TextView) root.findViewById(R.id.sign_up_privacy);
privacyTextView.setMovementMethod(LinkMovementMethod.getInstance());
Now the TextView links are clickable.
Second, We need to Handle these clicks:
In my Manifest file, I added intent-filter for "terms" and "privacy"
and Single Instance Launch Mode
<activity
android:name=".MyActivity"
android:launchMode="singleInstance">
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.VIEW"/>
<data android:scheme="terms"/>
<data android:scheme="privacy"/>
</intent-filter>
</activity>
In MyActivity, override onNewIntent to catch privacy and terms
intents
#Override
protected void onNewIntent(Intent intent)
{
if (intent.getScheme().equalsIgnoreCase(getString("terms")))
{
//handle terms clicked
}
else if (intent.getScheme().equalsIgnoreCase(getString("privacy")))
{
//handle privacy clicked
}
else
{
super.onNewIntent(intent);
}
}
The best way to do this is with string file
In string.xml
<string name="agree_to_terms">I agree to the %1$s and %2$s</string>
<string name="terms_of_service">Terms of Service</string>
<string name="privacy_policy">Privacy Policy</string>
In onCreateView call below method
private void setTermsAndCondition() {
String termsOfServicee = getString(R.string.terms_of_service);
String privacyPolicy = getString(R.string.privacy_policy);
String completeString = getString(R.string.agree_to_terms, termsOfServicee,privacyPolicy);
int startIndex = completeString.indexOf(termsOfServicee);
int endIndex = startIndex + termsOfServicee.length();
int startIndex2 = completeString.indexOf(privacyPolicy);
int endIndex2 = startIndex2 + privacyPolicy.length();
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(completeString);
ClickableSpan clickOnTerms = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(this, "click on terms of service", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ContextCompat.getColor(this, R.color.blue));
}
};
ClickableSpan clickOnPrivacy = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(this, "click on privacy policy", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ContextCompat.getColor(this, R.color.blue));
}
};
spannableStringBuilder.setSpan(clickOnTerms, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(clickOnPrivacy, startIndex2, endIndex2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(spannableStringBuilder);
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
With Textoo, this can be achieved like:
res/values/strings.xml:
<resources>
<string name="str_terms_and_privacy">By signing up you agree to our Terms of Service and Privacy Policy.</string>
</resources>
res/layout/myActivity.xml:
<TextView
android:id="#+id/view_terms_and_privacy"
android:text="#string/str_terms_and_privacy"
/>
java/myPackage/MyActivity.java:
public class MyActivity extends Activity {
...
protected void onCreate(Bundle savedInstanceState) {
...
TextView termsAndPrivacy = Textoo
.config((TextView) findViewById(R.id.view_terms_and_privacy))
.addLinksHandler(new LinksHandler() {
#Override
public boolean onClick(View view, String url) {
if ("terms:".equals(url)) {
// Handle terms click
return true; // event handled
} else if ("privacy:".equals(url)) {
// Handle privacy click
return true; // event handled
} else {
return false; // event not handled. continue default processing i.e. launch web browser and display the link
}
}
})
.apply();
...
}
...
}
This approach have the advantages that:
Keep text externalized as string resource. Make it easier to localize your app.
Can handle the click event directly using LinksHandler and no need to define additional intent filter
Simpler and more readable code
This is working for me :
in xml :
<TextView
android:id="#+id/tv_by_continuing_str"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:textSize="15sp"
tools:text="Test msg 1 2, 3"
android:textColor="#color/translucent_less_white3"
android:textColorLink="#color/white"
android:gravity="center|bottom"
android:layout_above="#+id/btn_privacy_continue" />
In strings.xml
< string name="by_continuing_str2">< ! [ CDATA[By continuing to use this app, you agree to our <a href="https://go.test.com" style="color:gray"/> Privacy Statement </a> and <a href="https://go.test.com" style="color:gray"/>Services Agreement.]]>< / string>
in the activity :
TextView tv_by_continuing = (TextView) findViewById(R.id.tv_by_continuing);
tv_by_continuing.setText(Html.fromHtml(getString(R.string.by_continuing_str2)));
tv_by_continuing.setMovementMethod(LinkMovementMethod.getInstance());
private fun customTextView(view: TextView) {
//I agree to the Terms of service & Privacy Policy,
val spanTxt = SpannableStringBuilder(
"I agree to the ")
spanTxt.append("Terms of service")
spanTxt.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
toast("Terms of service link clicked")
}
}, spanTxt.length - "Term of services".length, spanTxt.length, 0)
spanTxt.append(" and")
spanTxt.append(" Privacy Policy")
spanTxt.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
toast("Privacy Policy link clicked")
}
}, spanTxt.length - " Privacy Policy".length, spanTxt.length, 0)
view.movementMethod = LinkMovementMethod.getInstance()
view.setText(spanTxt, TextView.BufferType.SPANNABLE)
}
An easy fix for this would be to use multiple labels. One for each link and one for the text.
[TermsOfServiceLabel][andLabel][PrivacyPolicy]
Or is it necessary that you only use one label?
Related
Desired Behavior
In case it affects any answers or suggestions, what I would like to ultimately see in this app is a navigation UI where one of the Fragment is a map. I used a template to start with a navigation UI, which gave me several Fragments, one for each tab. Currently, I'm trying to use the Google API to put a MapView inside of one of those Fragments.
Current Behavior
Generally, this isn't working (obviously). I have everything up and running, but when I pull up the tab with the map in it, the map is blank. Nothing crashes, and no errors are output:
I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
Selected remote version of com.google.android.gms.googlecertificates, version >= 4
Other Details/Troubleshooting
I know that my API key works because I have another app in which the maps work as expected. I doubt I need a second API key, but I looked anyway and since it wasn't overly obvious how to create a second API key, I think that hunch is correct. Most of the code I'm using was copied from that working example; the primary difference is that other example uses a SupportMapFragment and it has a class MapsActivity extends FragmentActivity. Here, since I don't really want to deal with nesting fragments, I'm trying to use a MapView inside that fragment.
What bits of my code that weren't copied largely came from online sources. None of what I've tried has produced better results.
MapView inside fragment is answering a different problem
Creating google maps v2 in a fragment using Navigation Drawer contains only things I already have
android MapView in Fragment gave me the idea to use MapsInitializer.initialize(this.getActivity()); but that didn't help
Mapview in separate fragment android has nothing new
how do i solve integrating google map in fragment in android uses a Fragment not a MapView
I also know that onMapReady is being called. Inside of that, I move the camera and that subsequently calls onCameraMoveStarted. However, it does not enter onCameraMove or onCameraIdle.
Code
This is the code as it is, which uses some of the ideas from the above links. I tried to cut out anything that's unrelated (other fragments, etc)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.retailtherapy">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="stateVisible|adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
</manifest>
activity_main.xml
<androidx.constraintlayout.widget.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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation"
tools:context=".MainActivity" />
</androidx.constraintlayout.widget.ConstraintLayout>
mobile_navigation.xml
<navigation 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:id="#+id/mobile_navigation"
app:startDestination="#+id/navigation_map">
<fragment
android:id="#+id/navigation_map"
android:name="com.example.retailtherapy.ui.map.MapFragment"
android:label="Map"
tools:layout="#layout/fragment_map" />
</navigation>
fragment_map.xml
<RelativeLayout
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"
tools:context=".ui.map.MapFragment" >
<com.google.android.gms.maps.MapView
android:id="#+id/googleMap"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {
/*************************************************************************
*
* M E M B E R S
*
*/
// Location manager for getting current location
private LocationManager mLocationManager = null;
// The map object for reference for ease of adding points and such
private GoogleMap mGoogleMap = null;
private MapView mMapView = null;
// The camera position tells us where the view is on the map
private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();
// Current latitude and longitude of user
private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);
// These are flags that allow us to selectively not move the camera and
// instead wait for idle so the movement isn't jerky
private boolean mCameraMoving = false;
private boolean mPendingUpdate = false;
/*************************************************************************
*
* F R A G M E N T
*
*/
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_map, container, false);
// The google map...
MapsInitializer.initialize(getActivity());
mMapView = (MapView) root.findViewById(R.id.googleMap);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// The required permissions...
final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.INTERNET,
};
requestPermissions(REQUIRED_PERMISSIONS, 0);
return root;
}
#Override
public void onStart() throws SecurityException {
super.onStart();
// Location manager for getting info current location
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
/*************************************************************************
*
* G O O G L E M A P S
*
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// Assuming if here that we have permissions okay. Dangerous sure
// but I'm lazy...
mGoogleMap.setMyLocationEnabled(true);
// Store the location of the camera for UI purposes so we can go
// back to where we were
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
mCameraPosition = mGoogleMap.getCameraPosition();
}
});
mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
mCameraMoving = true;
}
});
mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
mCameraMoving = false;
if (mPendingUpdate) {
centerCameraOnLocation(false);
}
}
});
// Start with user centered in view
centerCameraOnLocation(true);
}
/*************************************************************************
*
* L O C A T I O N
*
*/
#Override
public void onLocationChanged(Location location) {
// Store the current location so if we start auto-center but aren't
// already, we know where to pan to
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
if (!newLatLng.equals(mCurrentLatLong)) {
mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
centerCameraOnLocation(false);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
/*************************************************************************
*
* M A P C A M E R A
*
*/
/*
* Updates the camera position based on current state. If the camera is
* already moving, then wait.
*/
private void centerCameraOnLocation(boolean animate) {
if (mGoogleMap == null) {
return;
}
if (mCameraMoving) {
mPendingUpdate = true;
return;
}
// Get the CameraPosition to update to based on whether we are auto
// centering or not.
if (mCameraPosition == null) {
mCameraPosition = Constants.GetDefaultCameraPosition();
}
// If this is the same as it was before, then don't reset it
if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
return;
}
// Make the update so we can move the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);
// Move the camera with or without animation. The time we don't want
// animation is when we're setting the position initially
if (animate) {
mGoogleMap.animateCamera(cameraUpdate);
}
else {
mGoogleMap.moveCamera(cameraUpdate);
}
mPendingUpdate = false;
}
}
FINALLY I found the answer in a comment at https://stackoverflow.com/a/51464293/3038157.
Basically, it seems there was something stale. Without changing any code, I uninstalled the app, cleaned the build, rebuilt, and voila it worked.
You must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class.
View this official guide
or example code
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
I have implemented a Searchview into my application, and have run into a weird problem. Basically, the user is able to enter a string to be searched and it is submitted properly. However, my application will filter the ListView based on the search query, and then an Intent will be launched resulting in the activity starting again and returning to it's original state where it is displaying all the results.
Here is the related code.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
updateEntriesView(dbHelper.queryByName(query));
Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
private void updateEntriesView(ArrayList<Entry> response) {
mListView = (ListView) findViewById(R.id.listview_entries);
if (adapter == null) {
adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(response);
adapter.notifyDataSetChanged();
}
adapter.setNotifyOnChange(true);
}
I can not figure out to change this behavior and I can not find any documentation regarding it's implementation online. Is there a way I can override this feature and prevent it from launching an intent and restarting the activity to it's original unfiltered state?
EDIT:
I was able to solve this issue myself. For anyone who may be having the same problem here was my solution.
So I had an intent-filter in my AndroidManifest.xml under the activity that would launch an intent upon a search action. This is what was causing it to launch an intent and start a new instance of my activity.
My solution to this was to convert this activity into a single top activity and add code to handle the intent. By making the activity single top, it allows the activity to handle incoming intents without starting up a new instance of the intent. For a more detailed description on the difference between a normal and single top activity, this is a good article on the subject https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/
Now, because my activity is single top, I can override the onNewIntent() method and add my code for handling this intent without having it launch a new instance. The relevant code for solving my problem is below.
AndroidManifest.xml
<activity android:name=".EntriesActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"></meta-data>
</activity>
EntriesActivity.java
public class EntriesActivity extends AppCompatActivity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
updateEntriesView(dbHelper.queryByName(query));
Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
updateEntriesView(dbHelper.queryEntriesByName(query));
}
}
private void updateEntriesView(ArrayList<Entry> response) {
if (adapter == null) {
adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response);
mEntriesList.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(response);
adapter.notifyDataSetChanged();
}
adapter.setNotifyOnChange(true);
}
}
I hope this helps.
You need to clear focus of the text view using searchView.clearFocus();
Refer This Answer: https://stackoverflow.com/a/15127252/7710739
I know this is old but if your searching and resulting in the same Activity try removing the
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
It should not try to launch a new activity then i don't beleive.
How i can send people to my google play on click certain button ?
i already did this in activity_menu.xml
<Button
android:id="#+id/ratebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/morebutton"
android:layout_alignBottom="#+id/morebutton"
android:layout_toLeftOf="#+id/morebutton"
android:layout_toRightOf="#+id/aboutButton"
android:background="#drawable/more"
android:text="#string/rateBtn"
android:textColor="#color/White"
android:textColorHint="#color/White"
android:textSize="18sp" />
but in MenuActivity.java i couldn't know what should i do ?
Any help? Thanks
findViewById(R.id.ratebutton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "market://details?id=<package_name>";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Button rate = (Button)findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2=new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=yourpackagename"));
startActivity(i2);
}
});
// Enter package name of application in place of yourpackagename
In my signin.xml file I put this code:
<Button
android:id="#+id/privacypolicylink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="50dp"
android:background="#android:color/transparent"
android:onClick="performSingUpMethod"
android:text="Política de Privacidad"
android:textColor="#A9A9A9"
android:textSize="15dp"
android:textStyle="bold" />
In my signin.java file I used this:
findViewById(R.id.privacypolicylink).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://example.net/privacy_policy";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
It works for me. It displays a text in the grey color that I want it. The text is underlined and it is a link. The is the way it looks:
When I click on it, I see this:
Then I can open the link using a web browser on the phone and everything works correctly the way I needed it.
Declare button inside your activity:
Button btnRateButton;
Initialize btnRateButton inside onCreate method:
btnRateButton = (Button) findViewById(R.id.ratebutton);
Set on click listener:
btnRateButton.setOnClickListener(this);
Write onclick method:
#Override
public void onClick(View v) {
Intent i = null;
final String myPackage = getPackageName();
if(v.getId() == R.id.btnRateButton) {
i = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=" + myPackage));
startActivity(i);
}
}
Note that for above code to work, you need to have Play Store app installed on your device.
I have been searching for a while now but can't find a working solution for my android code. Well at least one I am able to implement.
I have an activity (StartActivity) with a few animations. Then I have an onTouchEvent. This works fine to prompt a few more animations however after this I want to open a new Activity.
Here is my code:
public class StartActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
RunAnimations(R.anim.translate1, R.anim.translate2);
}
public void RunAnimations(int t1, int t2) {
Animation a = AnimationUtils.loadAnimation(this, t1);
a.reset();
Animation b = AnimationUtils.loadAnimation(this, t2);
b.reset();
ImageView drop = (ImageView) findViewById(R.id.drop);
ImageView iflush = (ImageView) findViewById(R.id.iflush);
drop.clearAnimation();
iflush.clearAnimation();
drop.startAnimation(a);
iflush.startAnimation(b);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
RunAnimations(R.anim.translate3, R.anim.translate4);
}
return true;
}
}
In the onTouchEvent, after calling RunAnimations, I want to start a new activity (TipActivity). That is all.
Add another activity to you AndroidManifest file like so:
<activity
android:label="YourActivity"
android:name=".YourActivity" >
<intent-filter >
<action android:name="net.learn2develop.YourActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And then you could do something like (after calling RunAnimations()) :
startActivity(new Intent("net.learn2develop.YourActivity"));
Hope that helps.
Use that:
Intent intent=new Intent(context, TipActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.translate3, R.anim.translate4);
^-^
i am developing an android application that has a shared preference, containing :
- Ringtone (done)
disable the dialog notification (alarm, SMS, MMS)(not yet,please read the comment inside the code)
-Tell friend (i am sure my code is right but i am not sure how to put it with Shared preference + i am now sure of place and method that i should put at it- please read to the comment inside the code)
public class Setting extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
String ringtonePreference;
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ringtonePreference = prefs.getString("ringtonePref",
"DEFAULT_RINGTONE_URI");
}
//disable all Notification (Alarm , SMS,MMS)
//what is the method that i should put this code at it? onStart?onDestroy?or what?
SharedPreferences sharedPreferences = this.getPreferences(MODE_PRIVATE);
boolean hideNotification = sharedPreferences.getBoolean("checkbox", false);
if(!hideNotification)
alertDialog.show();
}
//tell friend
//i am not sure if this is right place to this code
//if it is the right place then what is the method that i should put this code at it?onStart?onActivityResult?or what?
SharedPreferences prefs1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
TellFriendPreference = prefs1.getString("tellfriend","null");
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
String str= item.toString();
if(str=="Tell Friends"){
Toast.makeText(this,"First", Toast.LENGTH_LONG).show();
//Go to tell friend activity
//Intent i = new Intent (Help.this, .class);
//startActivity(i);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Check out s Application for Android. Download it today from http://s.com");
startActivity(Intent.createChooser(intent, "Tell friends:"));
startActivity(intent);
}
this is prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Second Category" >
<RingtonePreference
android:name="Ringtone Preference"
android:key="ringtonePref"
android:summary="Select a ringtone"
android:title="Ringtones" />
<CheckBoxPreference
android:defaultValue="true"
android:key="checkbox"
android:summary="Check the Box"
android:title="Disable Notification" />
<Preference
android:name="tell Preference"
android:key="tellfriend"
android:summary="if u want to tell ur friends by usinf"
android:title="Tell Friend" />
</PreferenceCategory>
</PreferenceScreen>
please help me, i should submit it after some hours
I solved my problem. I just but tell friend in another activity, my code is correct.