I have made a custom URL span to use the chrome custom tab to open a link. The links are getting displayed correctly, I use the Html.fromHtml() function.
In the activity I use this for the TextView:
content_txt_view = (TextView)findViewById(R.id.textView_news);
content_txt_view.setTransformationMethod(new LinkTransformationMethod());
content_txt_view.setMovementMethod(LinkMovementMethod.getInstance());
The linkstransformation class looks like this:
public class LinkTransformationMethod implements TransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
// Linkify.addLinks(textView, Linkify.WEB_URLS);
if (textView.getText() == null || !(textView.getText() instanceof Spannable)) {
return source;
}
Spannable text= new SpannableString(textView.getText());
URLSpan[] spans = text.getSpans(0, textView.length(), URLSpan.class);
for (int i = spans.length - 1; i >= 0; i--) {
URLSpan oldSpan = spans[i];
int start = text.getSpanStart(oldSpan);
int end = text.getSpanEnd(oldSpan);
String url = oldSpan.getURL();
text.removeSpan(oldSpan);
text.setSpan(new CustomTabsURLSpan(url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return text;
}
return source;
}
and the custom url span:
public class CustomTabsURLSpan extends URLSpan {
private Context context;
public CustomTabsURLSpan(String url) {
super(url);
Log.d("SensibleUrlSpan", "1");
}
public CustomTabsURLSpan(Parcel src) {
super(src);
Log.d("SensibleUrlSpan", "2");
}
#Override
public void onClick(View widget) {
Log.d("SensibleUrlSpan", "3");
String url = getURL();
Toast toast = Toast.makeText(context, "well done! you click ", Toast.LENGTH_SHORT);
toast.show();
// String url = "http://www.google.com";
}
}
I would have expected that when I click on the link, I will get the toast message...But it seems the OnClick method is not called at all.
The classes below implement the desired behaviour:
CustomClickURLSpan.java
import android.text.style.URLSpan;
import android.view.View;
public class CustomClickURLSpan extends URLSpan {
private OnClickListener mOnClickListener;
public CustomClickURLSpan(String url) {
super(url);
}
public void setOnClickListener(OnClickListener onClickListener) {
mOnClickListener = onClickListener;
}
#Override
public void onClick(View widget) {
if (mOnClickListener == null) {
super.onClick(widget);
} else {
mOnClickListener.onClick(widget, getURL());
}
}
public interface OnClickListener {
void onClick(View view, String url);
}
}
CustomTabsOnClickListener.java
import android.app.Activity;
import android.net.Uri;
import android.support.customtabs.CustomTabsIntent;
import android.view.View;
import java.lang.ref.WeakReference;
public class CustomTabsOnClickListener implements CustomClickURLSpan.OnClickListener {
private WeakReference<Activity> mActivityWeakReference;
private WeakReference<CustomTabActivityHelper> mCustomTabActivityHelperWeakReference;
public CustomTabsOnClickListener(Activity hostActivity,
CustomTabActivityHelper customTabActivityHelper) {
mActivityWeakReference = new WeakReference<>(hostActivity);
mCustomTabActivityHelperWeakReference = new WeakReference<>(customTabActivityHelper);
}
#Override
public void onClick(View view, String url) {
Activity activity = mActivityWeakReference.get();
CustomTabActivityHelper customTabActivityHelper =
mCustomTabActivityHelperWeakReference.get();
if (activity != null && customTabActivityHelper != null) {
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(null)
.build();
customTabsIntent.intent.setPackage(
CustomTabsHelper.getPackageNameToUse(view.getContext()));
customTabsIntent.launchUrl(activity, Uri.parse(url));
}
}
}
A Utility class with the linkifyUrl methods that creates Spans for the URLs
import android.text.Spannable;
import android.text.Spanned;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
private static final Pattern URL_PATTERN = Pattern.compile("((http|https|rstp):\\/\\/\\S*)");
public static void linkifyUrl(
Spannable spannable, CustomClickURLSpan.OnClickListener onClickListener) {
Matcher m = URL_PATTERN.matcher(spannable);
while (m.find()) {
String url = spannable.toString().substring(m.start(), m.end());
CustomClickURLSpan urlSpan = new CustomClickURLSpan(url);
urlSpan.setOnClickListener(onClickListener);
spannable.setSpan(urlSpan, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
Finally, invoke those classes to linkify the text:
TextView content = (TextView)findViewById(R.id.content);
Spannable spannable = new SpannableString(post.getText());
Util.linkifyUrl(spannable, new CustomTabsOnClickListener(this, mCustomTabActivityHelper));
content.setText(spannable);
content.setMovementMethod(LinkMovementMethod.getInstance());
The helper classes used are available on the Github Demo: CustomTabsHelper and CustomTabsActivityHelper
Related
I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.
this is the view that crashes when i click start but i dont know why
i think it has something to do with the threding in the bruteForce function
package com.my.app;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import java.util.*;
import java.text.*;
import android.test.*;
import android.view.animation.*;
import android.widget.Button;
public class TestActivity extends Activity {
private LinearLayout linear1;
private TextView original;
private TextView match;
private TextView text;
private Button bstart;
String attempt = new String();
boolean running;
int counter;
private String hash = "";
public String username = new String();
public static String password = "ZZZZZ";
public static char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static char[] currentGuess = new char[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
initialize();
initializeLogic();
}
private void initialize() {
linear1 = (LinearLayout) findViewById(R.id.linear1);
original = (TextView) findViewById(R.id.original);
match = (TextView) findViewById(R.id.match);
text = (TextView) findViewById(R.id.text);
bstart = (Button) findViewById(R.id.bstart);
bstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _v) {
bruteForce();
}
});
}
private void initializeLogic() {
Intent test = getIntent();
hash = test.getStringExtra("hash");
original.setText(password);
}
public void increment()
{
int index = currentGuess.length - 1;
while (index >= 0)
{
if (currentGuess[index] == charset[charset.length - 1])
{
if (index == 0)
{
currentGuess = new char[currentGuess.length + 1];
Arrays.fill(currentGuess, charset[0]);
break;
}
else
{
currentGuess[index] = charset[0];
index--;
}
}
else
{
currentGuess[index] = charset[Arrays.binarySearch(charset, currentGuess[index]) + 1];
break;
}
}
}
public String toString()
{
return String.valueOf(currentGuess);
}
public void bruteForce()
{
Animation animation = new Animation(){
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
text.setText(attempt);
}
};
animation.setRepeatCount(Animation.INFINITE);
text.startAnimation(animation);
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
}
#Override
protected void onStop() {
super.onStop();
running = false;
}
public void BruteForceTest()
{
Arrays.fill(currentGuess, charset[0]);
}
// created automatically
private void ShowMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
private int GetRandom(int _minValue ,int _maxValue){
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
public ArrayList<Integer> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Integer> _result = new ArrayList<Integer>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add(_arr.keyAt(_iIdx));
}
return _result;
}
}
Your problem lies here
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
You can only update an UI element from the main thread. If you want to do it likes this you need to wrap text.setText(attempt) with a handler that posts it to the main thread. e.g.
new Handler(Looper.getMainLooper()).post(new Runnable(){
void run() {
text.setText(attempt);
}
});
Looper.getMainLooper() (docs) will get the main application thread which the handler then posts the Runnable to .
if (attempt.equals(password))
{
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
text.setText(attempt);
}
});
this.stop();
}
Similarly wherever you are changing ui elements like setting text or changin colors do it in runOnUithread as I did above.
I am working on text-view.in that text-view display html hyperlink.
when i click on hyper-linked text then i want to get that text.
as per above image if i click on hyperlink, then i want to display text.
Your answer would be appreciated
The LinkEnableTextView class is like this:
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class LinkEnabledTextView extends TextView
{
// The String Containing the Text that we have to gather links from private SpannableString linkableText;
// Populating and gathering all the links that are present in the Text
private ArrayList<Hyperlink> listOfLinks;
// A Listener Class for generally sending the Clicks to the one which requires it
TextLinkClickListener mListener;
// Pattern for gathering #usernames from the Text
Pattern screenNamePattern = Pattern.compile('(#[a-zA-Z0-9_]+)');
// Pattern for gathering #hasttags from the Text
Pattern hashTagsPattern = Pattern.compile('(#[a-zA-Z0-9_-]+)');
// Pattern for gathering http:// links from the Text
Pattern hyperLinksPattern = Pattern.compile('([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\'>\\]\\)]*[^\\. ,'\'>\\]\\)])');
public LinkEnabledTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
listOfLinks = new ArrayList<Hyperlink>();
}
public void gatherLinksForText(String text)
{
linkableText = new SpannableString(text);
//gatherLinks basically collects the Links depending upon the Pattern that we supply
//and add the links to the ArrayList of the links
gatherLinks(listOfLinks, linkableText, screenNamePattern);
gatherLinks(listOfLinks, linkableText, hashTagsPattern);
gatherLinks(listOfLinks, linkableText, hyperLinksPattern);
for(int i = 0; i< listOfLinks.size(); i++)
{
Hyperlink linkSpec = listOfLinks.get(i);
android.util.Log.v('listOfLinks :: ' + linkSpec.textSpan, 'listOfLinks :: ' + linkSpec.textSpan);
// this process here makes the Clickable Links from the text
linkableText.setSpan(linkSpec.span, linkSpec.start, linkSpec.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
// sets the text for the TextView with enabled links
setText(linkableText);
}
// sets the Listener for later click propagation purpose
public void setOnTextLinkClickListener(TextLinkClickListener newListener)
{
mListener = newListener;
}
//The Method mainly performs the Regex Comparison for the Pattern and adds them to
//listOfLinks array list
private final void gatherLinks(ArrayList<Hyperlink> links,
Spannable s, Pattern pattern)
{
// Matcher matching the pattern
Matcher m = pattern.matcher(s);
while (m.find())
{
int start = m.start();
int end = m.end();
// Hyperlink is basically used like a structure for storing the information about
// where the link was found.
Hyperlink spec = new Hyperlink();
spec.textSpan = s.subSequence(start, end);
spec.span = new InternalURLSpan(spec.textSpan.toString());
spec.start = start;
spec.end = end;
links.add(spec);
}
}
// This is class which gives us the clicks on the links which we then can use.
public class InternalURLSpan extends ClickableSpan
{
private String clickedSpan;
public InternalURLSpan (String clickedString)
{
clickedSpan = clickedString;
}
#Override
public void onClick(View textView)
{
mListener.onTextLinkClick(textView, clickedSpan);
}
}
// Class for storing the information about the Link Location
class Hyperlink
{
CharSequence textSpan;
InternalURLSpan span;
int start;
int end;
}
Now, having this you require just another interface for propagating the clicks to the place you require to handle them in my case I implemented the interface in my Activity and simple wrote a Log Command there.
The TextLinkClickListener interface is like this:
import android.view.View;
public interface TextLinkClickListener
{
// This method is called when the TextLink is clicked from LinkEnabledTextView
public void onTextLinkClick(View textView, String clickedString)
}
After doing all this you just require to create an Activity using the Custom LinkEnabledTextView and check the things out yourself. There are a few things that you must do while creating a object of the Custom LinkEnabledTextView those are mentioned and described in the Code of the Activity below:
import android.text.method.MovementMethod;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.LinkEnabledTextView;
import com.umundoinc.Tvider.Component.LinkEnabledTextView.TextLinkClickListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
//Here the Activity is implementing the TextLinkClickListener the one we have created
//the Clicks over the Links are forwarded over here from the LinkEnabledTextView
public class TextViewActivity extends Activity implements TextLinkClickListener
{
private LinkEnabledTextView check;
protected void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
String text = "This is a #test of regular expressions with http://example.com/ links as used in #twitter for performing various operations based on the links this handles multiple links like http://this_is_fun.com/ and #Awesomess and #Cool";
check = new LinkEnabledTextView(this, null);
check.setOnTextLinkClickListener(this);
check.gatherLinksForText(text);
check.setTextColor(Color.WHITE);
check.setLinkTextColor(Color.GREEN);
MovementMethod m = check.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (check.getLinksClickable()) {
check.setMovementMethod(LinkMovementMethod.getInstance());
}
}
setContentView(check);
}
public void onTextLinkClick(View textView, String clickedString)
{
android.util.Log.v('Hyperlink clicked is :: ' + clickedString, 'Hyperlink clicked is :: ' + clickedString);
}
Hope it will help you!!
Please try my Implementation:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
textView mTvTxt = findViewById(R.id.tv_txt_view);
final String hyperlink = "Vasant jetava";
SpannableString spannableString = makeLinkSpan(hyperlink , new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(hyperlink)
}
});
mTvTxt.setText(getString("hello whats up man....");
mTvTxt.append(spannableString);
makeLinksFocusable(mTvTxt);
}
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
#Override
public void onClick(View v) {
mListener.onClick(v);
}
}
private void showDialog(String message){
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage(message);
alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
What I want the app to do after scanning is to dial the number instead of displaying it.So I'm new to Android developing and zxing library. I've been able to create a standalone QR scanner app using the zxing library but the issue is that when it scans the QR code, I want it to either open the URL in a browser or do something else based on the content of the QR instead of displaying the string content of the QR code. Example, if the string content of the QR code is a URL "www.stackoverflow.com", I want the app to take me to the site instead of displaying the string content of the QR code.
This is the code for my CaptureActivity
package com.skyers.jwetherell.quick_response_code;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.skyers.google.zxing.Result;
import com.skyers.google.zxing.ResultMetadataType;
import com.skyers.jwetherell.quick_response_code.result.ResultHandler;
import com.skyers.jwetherell.quick_response_code.result.ResultHandlerFactory;
import java.text.DateFormat;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
public class CaptureActivity extends com.skyers.jwetherell.quick_response_code.DecoderActivity {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet.of(ResultMetadataType.ISSUE_NUMBER, ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL, ResultMetadataType.POSSIBLE_COUNTRY);
private TextView statusView = null;
private View resultView = null;
private boolean inScanMode = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.capture);
Log.v(TAG, "onCreate()");
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
inScanMode = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy()");
}
#Override
protected void onResume() {
super.onResume();
Log.v(TAG, "onResume()");
}
#Override
protected void onPause() {
super.onPause();
Log.v(TAG, "onPause()");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inScanMode)
finish();
else
onResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void handleDecode(Result rawResult, Bitmap barcode) {
drawResultPoints(barcode, rawResult);
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
handleDecodeInternally(rawResult, resultHandler, barcode);
}
protected void showScanner() {
inScanMode = true;
resultView.setVisibility(View.GONE);
statusView.setText(R.string.msg_default_status);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
}
protected void showResults() {
inScanMode = false;
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
}
// Put up our own UI for how to handle the decodBarcodeFormated contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
onPause();
showResults();
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.skyers));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formattedTime);
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
}
}
And this is the code for my ResultHandler
package com.skyers.jwetherell.quick_response_code.result;
import android.app.Activity;
import com.skyers.google.zxing.Result;
import com.skyers.google.zxing.client.result.ParsedResult;
import com.skyers.google.zxing.client.result.ParsedResultType;
public abstract class ResultHandler {
private final ParsedResult result;
private final Activity activity;
private final Result rawResult;
ResultHandler(Activity activity, ParsedResult result) {
this(activity, result, null);
}
ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
this.result = result;
this.activity = activity;
this.rawResult = rawResult;
}
public ParsedResult getResult() {
return result;
}
Activity getActivity() {
return activity;
}
public Result getRawResult() {
return rawResult;
}
public boolean areContentsSecure() {
return false;
}
public CharSequence getDisplayContents() {
String contents = result.getDisplayResult();
return contents.replace("\r", "");
}
public abstract int getDisplayTitle();
public final ParsedResultType getType() {
return result.getType();
}
}
You question is not very clear, you have to put some source code to explain your issue.
You could use this library: https://github.com/zxing/zxing/wiki/Scanning-Via-Intent
and in your activity:
private void launchScanBarcode(){
IntentIntegrator integrator = new IntentIntegrator(yourActivity);
integrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result with scanResult.getContents() or scanResult.getRawBytes()
}
// else continue with any other code you need in the method
...
}
I am getting the text from API, can be random, but It contains expressions like on FB
#xyz hi, #abc how u??
1. I need to create a regex expression starts with #, ends with space.
2. Linkify it to open the user activity like XYZ or ABC.
Please help me, I have tried to create a class like,
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
public class ClickSpan extends ClickableSpan {
private OnClickListener mListener;
public ClickSpan(OnClickListener listener) {
mListener = listener;
}
#Override
public void onClick(View widget) {
if (mListener != null) mListener.onClick();
}
public interface OnClickListener {
void onClick();
}
/**
* To clickify a textview
* #param view
* #param clickableText
* #param listener
*/
public static void clickify(TextView view, final String clickableText,
final ClickSpan.OnClickListener listener) {
CharSequence text = view.getText();
String string = text.toString();
ClickSpan span = new ClickSpan(listener);
int start = string.indexOf(clickableText);
int end = start + clickableText.length();
if (start == -1) return;
if (text instanceof Spannable) {
((Spannable)text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
SpannableString s = SpannableString.valueOf(text);
s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(s);
}
MovementMethod m = view.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
view.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
And call like,
clickify(textView, clickText,new ClickSpan.OnClickListener()
{
#Override
public void onClick() {
startActivity here..
}
});
I need help as to how I can get this to work on my activity creating a loop of regex.
public class ClickableURLSpan extends URLSpan {
public ClickableURLSpan(String url) {
super(url);
}
#Override
public void onClick(View widget) {
String clickedText = getURL();
// START your activity here
}
}
Now you can linkify your text:
CharSequence input = "#xyz hi, #abc how u??!";
SpannableStringBuilder builder = new SpannableStringBuilder(input);
Pattern pattern = Pattern.compile("#.*?\\s");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
String text = input.subSequence(start, end).toString();
ClickableURLSpan url = new ClickableURLSpan(text);
builder.setSpan(url, start, end, 0);
}
textView.setText(builder);
textView.setMovementMethod(LinkMovementMethod.getInstance());