Spannable String in Fragment - java

Im using a SpannableString to color the words which match an existing string.
This works perfectly the first time the fragment is called, the words are found, matched and colored. But the second time the fragment is called, the method which checks for matches and colors the matching words fires, and from the log cat I can see the words are found and matched but not colored.
I'm guessing it has something to do with the lifecycle of the fragment and where SpannableString is being initialized.
I have tried to initialize the SpannableString in onResume(); and in setUserVisibleHint(boolean isVisibleToUser);
This is my approach
public class LessonOne extends ActualFragmetHolder {
#Override
public void init(Bundle savedInstanceState) {
addSlide(FragmentPronounce.newInstance("The cat is jumping over the mouse"));
addSlide(FragmentPronounce.newInstance("This house is really big"));
.....
FragmentPronounce.java
public class FragmentPronounce extends Fragment implements View.OnClickListener,RecognitionListener,TextToSpeech.OnInitListener {
private static final String ARG_OPTION_ONE = "opt1";
private SpannableString hashText;
....
public static FragmentPronounce newInstance(String option1) {
FragmentPronounce sampleSlide = new FragmentPronounce();
Bundle args = new Bundle();
args.putString(ARG_OPTION_ONE, option1);
sampleSlide.setArguments(args);
return sampleSlide;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
if (getArguments() != null && getArguments().size() != 0) {
option1 = getArguments().getString(ARG_OPCTION_ONE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pronounce_material, container, false);
final TextView the_question = (TextView) v.findViewById(R.id.text_user_must_say);
if (theQuestion != 0) {
the_question.setText(theQuestion);
}
//mic button
fabMic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
///starts listening for speech and does its thing
///Im using my own custom speech recognition which works fine
speech.startListening(recognizerIntent);
////check for OnResults()
}
}
#Override
public void onResults(Bundle results) {
//if its a OnResults is fine then
methodToCheckAnswer(results);
....
}
private void methodToCheckAnswer(Bundle results) {
//checks answer and calls method which counts and colors words in string
countAndColorWords();
}
//This is the method which check and colors, it triggers fine every time fragment is called, but it only colors the word the first time is called in the fragment's life cycle
private void countAndColorWords(){
String strRight = rightanswer;
.....
the_question = (TextView) getActivity().findViewById(R.id.text_user_says);
the_question.setText(theQuestion);
System.out.println("The question's TEXT" + String.valueOf(the_question.getText().toString()) + "Tokens counted" + tokensCounted + "Option1" + option1 + "What was spoken " + userAnswered);
hashText = SpannableString.valueOf(the_question.getText().toString());
System.out.println("hashText Value "+hashText+ "Right Answer "+ rightanswer);
Matcher matcher = Pattern.compile("\\S+").matcher(strRight);
Matcher usermatcher = Pattern.compile("\\S+").matcher(userAnswered);
int groupCounted = 0;
groupCounted += matcher.groupCount()+1;
Log.d(TAG, "The position number of groups:"+groupCounted +" "+userAnswered);
int rightAnswerCount = matcher.groupCount();
int userAnswerCount = usermatcher.groupCount();
String rightAnswer;
String userAnswer;
int contadorGroup = 0;;
int matchCounter =0;
contadorGroup += matcher.groupCount() + 1;
while (matcher.find() && usermatcher.find()) {
System.out.println(matcher.start() + ":" + matcher.group());
rightAnswer = matcher.group();
userAnswer = usermatcher.group();
rightAnswerCount += matcher.groupCount();
userAnswerCount += usermatcher.groupCount();
String check = "";
for (int i = 0; i <= rightAnswerCount && i <= userAnswerCount; i++) {
if (matcher.group(i).equalsIgnoreCase(usermatcher.group(i))) {//matcher.group(i) == usermatcher.group(i)
matchCounter++;
check = matcher.group(i);
hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#64DD17")), matcher.start(), matcher.end(), i);
}
}
}
//hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#64DD17")), matcher.start(), matcher.end(), palabraColor);
the_question.setText(hashText);
}
Sorry for spaghetti code, tried cleaning it up best I could after trying 100 different things.

Related

how can i underline a text word by word?

how can i underline word by word in a sentence in android studio? so my program would be like this if i click a button the underline will start at first and when i click again the button it will move again to the next word.
for Example:
_The_ *** *** ***** **** *** **** ***.
so if i want to click the button the underline will move next to it word or 3 asterisk.
The _***_ *** ***** **** *** **** ***.
and click again to the next asterisk.
this is my code using for this:
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txt = findViewById(R.id.display);
txt.setText("the red fox jumps over the lazy dog.");
final String [] compare1 = txt.getText().toString().split("\\s");
final String arr[] = txt.getText().toString().split(" ",2);
final String fword = arr[0];
String rword = arr[1];
final String reprword = rword.replaceAll("[a-z]", "*");
txt.setText(fword + " " + reprword);
final String [] display = txt.getText().toString().split("\\s");
/*final ArrayList<String> getters = new ArrayList<String>(Arrays.asList(display));*/
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(counter <= display.length) {
if(compare1[counter].length() == display[counter].length())
{
txt.setText(formatText(fword + " " + reprword,display[counter]));
}
counter++;
}
else
{
}
}
});
}
public CharSequence formatText(String base, String highlight) {
int start = base.indexOf(highlight);
if (start >= 0) {
SpannableString span = new SpannableString(base);
span.setSpan(new UnderlineSpan(), start, start + highlight.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
return base;
}
}
I change the other half the sentence to test it for this.
base.indexOf(highlight) ==> indexOf() returns the first occurrence of highlight in base , thats why the underline span jumps to first "the" instead of the next occurrence. You can use indexOf(String str, int fromIndex).
The following code tracks the "fromIndex" in this variable "nextStartIndex", and also underlining resets to first word after completing the sentence.
public class UnderlineWordsActivity extends AppCompatActivity {
private Button btn;
private TextView txt;
private int counter=0;
private int nextStartIndex=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txt = findViewById(R.id.display);
txt.setText("the red fox jumps over the lazy dog.");
final String[] arr = txt.getText().toString().split(" ", 2);
final String firstWord = arr[0];
String remainingWords = arr[1];
final String reprword = remainingWords.replaceAll("[a-z]", "*");
String text = firstWord+" "+reprword;
txt.setText(text);
final String[] display = txt.getText().toString().split("\\s");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter >= display.length) {
counter = 0;
nextStartIndex = 0;
}
txt.setText(formatText(text, display[counter]));
counter++;
}
});
}
public CharSequence formatText(String base, String highlight) {
int start = base.indexOf(highlight,nextStartIndex);
nextStartIndex = start+highlight.length();
if (start >= 0) {
SpannableString span = new SpannableString(base);
span.setSpan(new UnderlineSpan(), start, nextStartIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
return base;
}
}

Spannable string returning whole string on click

Using Button on a row in the ListView and am able to make a single row Spannable and data from database but when i click it is returning whole string than a word here is my code from MyAdapter Class where am entering values from database to Listview
public View getView(int i, View view, ViewGroup viewGroup) {
Realm realm=Realm.getDefaultInstance();
Word toEdit = realm.where(Word.class)
.equalTo("id", 10).findFirst();
int id_to_seperate=toEdit.getLang();
LayoutInflater inflater= (LayoutInflater) Main.context.getSystemService(Main.context.LAYOUT_INFLATER_SERVICE);
View row= inflater.inflate(R.layout.layout,viewGroup,false);
TextView word= (TextView) row.findViewById(R.id.word_name);
TextView meaning= (TextView) row.findViewById(R.id.word_define);
Word temp=list.get(i);
int idz=temp.getId();
word.setText(temp.getWord());
if(id_to_seperate==idz){
String span[] = temp.getMeaning().substring(1).split(" ") ;
SpannableString ss = new SpannableString(temp.getMeaning().substring(1));
ClickableSpan spans[] = new ClickableSpan[span.length];
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
int start = 0 ;
int end =0;
try {
for(int spanCount = 0 ; spanCount <span.length ; spanCount++){
if(spanCount==0) {
end += span[spanCount].length();
}else{
end += span[spanCount].length()+1;
}
ss.setSpan(spans[spanCount], start, end , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += span[spanCount].length()+1;
}
} catch (Exception e) {
e.printStackTrace();
}
meaning.setText(ss);
meaning.setMovementMethod(LinkMovementMethod.getInstance());
}else {
meaning.setText(temp.getMeaning().substring(1));
}
return row;
}
am able to get result from a specific row in a list
to this But click Functionality returning whole sentense than a span or word, I would be thankful if anyone can tell me what mistake I have done
Regards
here is wrong in your code
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
TextView.getText().toString() is return full text. if you want to get specific ClickableSpan then use below ClickableSpan
public class SpecialClickableSpan extends ClickableSpan {
String text;
public SpecialClickableSpan(String text){
super();
this.text = text;
}
#Override
public void onClick(View widget) {
Log.d(TAG, "onClick [" + text + "]");
}
}
replace
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
with
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new SpecialClickableSpan (span[spanCount ]);
}

Check ArrayList contains any data

I've 3 ScreenSlidePageFragment objects. I'm showing my data by parsing a json file. Here is my main activity code :
public class ScheduleMainActivity extends FragmentActivity {
/*
* Parsing JSON to get the array length
*/
private void getLength() {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
totalPages = jsonArray.length();
for(int counter = 0 ; counter < NUM_PAGES ; counter ++){
JSONObject jsonObject = jsonArray.getJSONObject(counter);
String getDate = jsonObject.getString("date");
ScheduleItem.dateWay.add(getDate);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static int totalPages; //value = 3
/**/
/**
* The pager widget, which handles animation and allows swiping horizontally
* to access previous and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
getLength();
mPager = (ViewPager)findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
supportInvalidateOptionsMenu();
}
});
}
/**
* A simple pager adapter that represents ScreenSlidePageFragment objects,
* in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
//Log.e("#MA", position + "");
return ScheduleSlideFragment.create(position, mPager);
}
#Override
public int getCount() {
return totalPages;
}
}
}
Now, I want to check if any previous date contains in data ArrayList. So, I tried this
if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){
jsonParseData(getPageNumber);
}
And It throws IndexOutOfBoundsException: Invalid index 0, size is 0.
Here is my ScheduleSlideFragment code
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
private static int pageNumber;
final static int totalPages = ScheduleMainActivity.totalPages;
//#SuppressWarnings("unchecked")
//public List<ScheduleItem>[] data = (ArrayList<ScheduleItem>[])new ArrayList[totalPages];
public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
public int getPageNumber;
private void jsonParseData(int _getPageNumber) {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
// Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
_getPageNumber = getPageNumber;
JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
String getDate = jsonObject.getString("date");
JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));
for (int i = 0; i < getFirstArray.length(); i++) {
JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
String time = getJSonObj.getString("time");
//Log.e("Time Log",time);
String type = getJSonObj.getString("type");
String title = getJSonObj.getString("title");
int typeId = getJSonObj.getInt("type_id");
data.add(new ScheduleItem(time, title, typeId, getDate));
/*
* Get Events
*/
if (typeId == 0) {
JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));
for (int j = 0; j < getEventsArray.length(); j++) {
JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
int typeEventId = getJSonEventobj.getInt("type_id");
if (typeEventId == 1) {
String EventInfo = getJSonEventobj.getString("info");
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
typeEventId, getDate));
} else {
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
getDate));
}
}
}
}
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
getPageNumber = pageNumber;
/**
* JSON Parsing
*/
if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){
jsonParseData(getPageNumber);
}
/**
* Set header date
*/
((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
final ListView list = (ListView)rootView.findViewById(R.id.list);
BinderData bindingData = new BinderData(this.getActivity(), data);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (data.get(position).getItemType() == 0
|| data.get(position).getItemType() == 3
|| data.get(position).getItemType() == 2)
return;
Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
ContentExtended.class);
intent.putExtra("title", data.get(position).getTitle());
intent.putExtra("content", data.get(position).getContent());
startActivity(intent);
}
});
ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
if (pageNumber == 0)
ibLeft.setVisibility(View.INVISIBLE);
else
ibLeft.setVisibility(View.VISIBLE);
ibLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() > 0)
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
});
ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
if (pageNumber + 1 == totalPages)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < totalPages)
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
});
return rootView;
}
public static Fragment create(int position) {
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
public static Fragment create(int position, ViewPager _pager) {
pageNumber = position;
pager = _pager;
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
}
}
My main problem is :
The data array contains all the data for one day/page at each position. In the current implementation(Without If condition), whenever someone opens say page three all data for page three is loaded, converted and stored in data at position 2.If we use such a data array the individual entries should not be recreated all of the time. So, I want to use a if condition to check data is available.
My Question is :
1) What are the alternatives way to way to check if data ArrayList contains any data??
2)How can I solve the the IndexOutOfBoundsException problem?
1) What are the alternatives way to way to check if data ArrayList
contains any data??
To check if an ArrayList contains any data, use the isEmpty() method, like so:
ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
if (!data.isEmpty()) { //data is not empty, meaning there is data....
2)How can I solve the the IndexOutOfBoundsException problem?
IndexOutOfBoundsException is thrown when you try to get an item in an indexed position that is out of range.
Out of range is when between [0, size() - 1] where size() is the size of the ArrayList().
To simply check if you're out of bounds, do something of this effect...
if ( i < 0 || i >= size()) { // Don't get item from an ArrayList, it's out of bounds
In your case:
if ( _getPageNumber >=0 && _getPageNumber < data.size()) { //Get item from jsonArray...
I hope this helps.
Answering your questions
1) You can check if data has any data with if (data != null && data.size() > 0)
2) You can avoid IndexOutOfBoundsException by validating that if (getPageNumber > 0 && getPageNumber < data.size())
I think first place to look for general purpose java APIs is Apache Commons. For your particular case (check if a collection is not empty) - see http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/CollectionUtils.html#isEmpty%28java.util.Collection%29.

Java : Recommended way to check a certain data already exists in the ArrayList

I have jsonParse method inside a onCreateView. I have 3 pages in my application. Every time, when I
open a page data created all of the time and I want to check therefore whether there is already something at the current position. Now, my question is what are recommended way to check a certain data already exists in the ArrayList.
Here is my code :
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
public static int pageNumber;
public static int PAGE_NUM = ScheduleMainActivity.NUM_PAGES ;
public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
public int getPageNumber;
private void jsonParseData(int _getPageNumber) {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
// Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
_getPageNumber = getPageNumber;
JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
String getDate = jsonObject.getString("date");
// data.add(new ScheduleItem(getDate));
JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));
for (int i = 0; i < getFirstArray.length(); i++) {
JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
String time = getJSonObj.getString("time");
//Log.e("Time Log",time);
String type = getJSonObj.getString("type");
String title = getJSonObj.getString("title");
int typeId = getJSonObj.getInt("type_id");
data.add(new ScheduleItem(time, title, typeId, getDate));
Log.e("Check Size", String.valueOf(data.size()));
/*
* Get Events
*/
if (typeId == 0) {
JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));
for (int j = 0; j < getEventsArray.length(); j++) {
JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
int typeEventId = getJSonEventobj.getInt("type_id");
if (typeEventId == 1) {
String EventInfo = getJSonEventobj.getString("info");
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
typeEventId, getDate));
} else {
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
getDate));
}
}
}
}
//Log.e("Check Date", String.valueOf(data.get(_getPageNumber).getDate()));
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
getPageNumber = pageNumber;
/**
* JSON Parsing
*/
checker = getPageNumber + 1;
jsonParseData(getPageNumber);
/**
* Set header date
*/
((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
final ListView list = (ListView)rootView.findViewById(R.id.list);
BinderData bindingData = new BinderData(this.getActivity(), data);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (data.get(position).getItemType() == 0
|| data.get(position).getItemType() == 3
|| data.get(position).getItemType() == 2)
return;
Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
ContentExtended.class);
intent.putExtra("title", data.get(position).getTitle());
intent.putExtra("content", data.get(position).getContent());
startActivity(intent);
}
});
ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
if (pageNumber == 0)
ibLeft.setVisibility(View.INVISIBLE);
else
ibLeft.setVisibility(View.VISIBLE);
ibLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() > 0)
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
});
ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
if (pageNumber + 1 == PAGE_NUM)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < PAGE_NUM)
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
});
return rootView;
}
public static Fragment create(int position) {
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
public static Fragment create(int position, ViewPager _pager) {
pageNumber = position;
pager = _pager;
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
}
}
If the objects inside the ArrayList has the equal methods properly overridden and defined you can use the contains method.
Whenever you need to check if your List contains something, you should use Set instead of List. HashSet for example.

why not display two picture in text?

When I type S in text1 a corresponding picture appears in text2 however when I type G in text1 a corresponding picture is shown in text2, but the previous picture of S is shown as a letter instead of a picture. Why is that? Why can't it display two pictures? What's wrong?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText te1 = (EditText)findViewById(R.id.t1);
final EditText te2 = (EditText)findViewById(R.id.t2);
final Button v = (Button)findViewById(R.id.b1);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//imva.setImageResource(R.id.b1);
te2.setText(" ");
String t= te1.getText().toString();
char [] aa = t.toString().toCharArray();
for (int i = 0 ; i < aa.length ; i++)
{
if (aa[i] == 's')
{
SpannableStringBuilder builder = new SpannableStringBuilder(te1.getText());
do {
ImageSpan imageSpan = new ImageSpan(getBaseContext(),R.drawable.a1);
int pos = builder.toString().indexOf("s");
builder.replace(pos, pos + 1, "$");
builder.setSpan(imageSpan, pos, pos + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} while (builder.toString().indexOf("s") > -1);
te2.setText(builder);
}
if (aa[i] == 'g')
{
SpannableStringBuilder builder = new SpannableStringBuilder(te1.getText());
do {
ImageSpan imageSpan = new ImageSpan(getBaseContext(),R.drawable.a2);
int pos = builder.toString().indexOf("g");
builder.replace(pos, pos+ 1, "$");
builder.setSpan(imageSpan, pos, pos + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} while (builder.toString().indexOf("g") > -1);
te2.setText(builder);
}
}

Categories

Resources