I have a ListView that can have new rows appended onto the bottom by calling notifyDataSetChanged(); and increasing the line count by 1. The ListView contains rows of EditTexts.
After calling notifyDataSetChanged(); I want to keep the values that have previously been entered by the user. It seems to be working as long as I don't go back and update one of the values I have already entered after calling notifyDataSetChanged();. Code is below:
public class AddPeopleNewProcedureActivity extends AppCompatActivity {
private ListView addPeopleListView;
private CustomAdapterClass customAdapter;
private FloatingActionButton fab;
private int lineCount;
private EditText personsNameET;
private EditText personsPhoneET;
private List<String> personsName;
private List<String> personsPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addpeoplenew_activity);
setupActivityReferences();
inflateListView();
setupClickListeners();
}
private void setupClickListeners() {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lineCount = lineCount +1;
customAdapter.notifyDataSetChanged();
}
});
}
private void inflateListView() {
customAdapter = new CustomAdapterClass();
addPeopleListView.setAdapter(customAdapter);
}
private void setupActivityReferences() {
addPeopleListView = (ListView) findViewById(R.id.listViewAddPeople);
fab = findViewById(R.id.fabAddPerson);
lineCount = 1;
personsName = new ArrayList<String>();
personsPhone = new ArrayList<String>();
}
public class CustomAdapterClass extends BaseAdapter {
#Override
public int getCount() {
return lineCount;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = getLayoutInflater().inflate(R.layout.row_addpersonnew,null);
}
personsNameET = (EditText) view.findViewById(R.id.personNameEditText);
personsPhoneET = (EditText) view.findViewById(R.id.personPhoneNoEditText);
final int rowClicked = i;
if (personsName != null && !personsName.isEmpty() && !(rowClicked >= personsName.size())){
personsNameET.setText(personsName.get(rowClicked));
}
if (personsPhone != null && !personsPhone.isEmpty() && !(rowClicked >= personsPhone.size())){
personsPhoneET.setText(personsPhone.get(rowClicked));
}
personsNameET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(!personsName.isEmpty()){
if (!(rowClicked >= personsName.size())){
personsName.set(rowClicked,personsNameET.getText().toString());
System.out.println("Set "+rowClicked + "Value is: " + personsName.get(rowClicked));
}else{
personsName.add(rowClicked,personsNameET.getText().toString());
System.out.println("Added" +rowClicked + "Value is: " + personsName.get(rowClicked));
}
} else{
personsName.add(rowClicked,personsNameET.getText().toString());
System.out.println("Added" +rowClicked + "Value is: " + personsName.get(rowClicked));
}
}
});
personsPhoneET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
}
}
You are using twice this code snippet in your code. Please remove blank one :
personsPhoneET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Do like this :
public class AddPeopleNewProcedureActivity extends AppCompatActivity {
private ListView addPeopleListView;
private CustomAdapterClass customAdapter;
private FloatingActionButton fab;
private int lineCount;
private EditText personsNameET;
private EditText personsPhoneET;
private List<String> personsName;
private List<String> personsPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addpeoplenew_activity);
setupActivityReferences();
inflateListView();
setupClickListeners();
}
private void setupClickListeners() {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lineCount = lineCount +1;
customAdapter.notifyDataSetChanged();
}
});
}
private void inflateListView() {
customAdapter = new CustomAdapterClass();
addPeopleListView.setAdapter(customAdapter);
}
private void setupActivityReferences() {
addPeopleListView = (ListView) findViewById(R.id.listViewAddPeople);
fab = findViewById(R.id.fabAddPerson);
lineCount = 1;
personsName = new ArrayList<String>();
personsPhone = new ArrayList<String>();
}
public class CustomAdapterClass extends BaseAdapter {
#Override
public int getCount() {
return lineCount;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = getLayoutInflater().inflate(R.layout.row_addpersonnew,null);
}
personsNameET = (EditText) view.findViewById(R.id.personNameEditText);
personsPhoneET = (EditText) view.findViewById(R.id.personPhoneNoEditText);
final int rowClicked = i;
if (personsName != null && !personsName.isEmpty() && !(rowClicked >= personsName.size())){
personsNameET.setText(personsName.get(rowClicked));
}
if (personsPhone != null && !personsPhone.isEmpty() && !(rowClicked >= personsPhone.size())){
personsPhoneET.setText(personsPhone.get(rowClicked));
}
personsNameET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(!personsName.isEmpty()){
if (!(rowClicked >= personsName.size())){
personsName.set(rowClicked,personsNameET.getText().toString());
System.out.println("Set "+rowClicked + "Value is: " + personsName.get(rowClicked));
}else{
personsName.add(rowClicked,personsNameET.getText().toString());
System.out.println("Added" +rowClicked + "Value is: " + personsName.get(rowClicked));
}
} else{
personsName.add(rowClicked,personsNameET.getText().toString());
System.out.println("Added" +rowClicked + "Value is: " + personsName.get(rowClicked));
}
}
});
}
Related
i have a search functionality in my app and although is it very limited due to the firebase firestore database queries, i managed to make it work to find string that match the beginning of the user's input.
now everything works fine, even when i write a string for instance "starbucks" and i slowly delete it character by character it resets my recyclerView to full shops available and not only starbucks.
but when i delete quickly (press down on the back button in the keyboard), it stops at that specific shop and doesnt refresh.
what is causing this?
here is my search adapter:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchAdapterViewHolder> {
public Context c;
public ArrayList<Shop> arrayList;
public SearchAdapter(Context c,ArrayList<Shop> arrayList){
this.c = c;
this.arrayList = arrayList;
}
#Override
public int getItemCount(){
return arrayList.size();
}
#Override
public long getItemId(int position){
return position;
}
#NonNull
#Override
public SearchAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_item,parent,false);
return new SearchAdapterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull SearchAdapterViewHolder holder, int position) {
final Shop shop = arrayList.get(position);
holder.list_name.setText(shop.getName());
String removeBraces = shop.getLocation();
String removeLeftBrace = removeBraces.replace("[","");
String removeRightBrace = removeLeftBrace.replace("]","");
holder.list_location.setText(removeRightBrace);
holder.list_overallRating.setText(""+shop.getRatings());
holder.setHeaderImage(shop.getShopHeaderImg());
holder.list_profileImage(shop.getShopProfileImg());
holder.cardLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("shopModel", shop);
context.startActivity(intent);
}
});
}
public class SearchAdapterViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout cardLayout;
private TextView list_name;
private TextView list_location;
private TextView list_overallRating;
private ImageView header_img;
private ImageView list_profileImage;
public SearchAdapterViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_location = itemView.findViewById(R.id.list_location);
list_overallRating = itemView.findViewById(R.id.list_overallRating);
header_img = itemView.findViewById(R.id.header_img);
list_profileImage = itemView.findViewById(R.id.list_profileImage);
cardLayout = itemView.findViewById(R.id.cardLayout);
}
public void setHeaderImage(final String Image) {
final ImageView headerImg = (ImageView)itemView.findViewById(R.id.header_img);
Picasso.get().load(Image).into(headerImg);
}
public void list_profileImage( final String image) {
final ImageView profileImg = (ImageView)itemView.findViewById(R.id.list_profileImage);
Picasso.get().load(image).into(profileImg);
}
}
}
here is my addTextChangeListener:
searchShops.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
searchInDB("");
}
}
});
and here is my searchInDB function:
private void searchInDB(final String s) {
firebaseFirestore.collection("Shops").orderBy("searchName").startAt(s).endAt(s+"\uf8ff").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
QuerySnapshot querySnapshot = task.getResult();
if(!querySnapshot.isEmpty()){
arrayList.clear();
for(QueryDocumentSnapshot DocumentSnapshot : querySnapshot) {
final Shop shop = DocumentSnapshot.toObject(Shop.class);
arrayList.add(shop);
}
SearchAdapter searchAdapter = new SearchAdapter(getApplicationContext(),arrayList);
recyclerView.setAdapter(searchAdapter);
searchAdapter.notifyDataSetChanged();
}else{
arrayList.clear();
}
}else{
}
}
});
Change:
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
searchInDB("");
}
To
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
recyclerView.setAdapter(null);
}
I am developping an application that needs a ListView with currency masked EditText and a summary TextView showing the sum of the items.
I made a custom adapter. The currency mask (format BRL R$ 0.000,00) is working.
How to make it sum the values when user types in the EditText of each item?
Here is the code of Adapter:
public AdapterFaturamentoMes(Context context, ArrayList<FaturamentoMes> lista) {
this.context = context;
this.lista = lista;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
FaturamentoMes item = lista.get(position);
View view = convertView;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.layout_lista_faturamento_mes, parent, false);
}
TextView txtFaturamentoMes = view.findViewById(R.id.txtFaturamentoMes);
EditText edFaturamento = view.findViewById(R.id.edFaturamento);
txtFaturamentoMes.setText(String.format(context.getString(R.string.txt_faturamento_mes), numberFormat.format(item.getMes()), numberFormat.format(item.getAno())));
edFaturamento.setText(decimalFormat.format(item.getValor()));
TextWatcher oldListener = (TextWatcher) edFaturamento.getTag();
if (oldListener != null) edFaturamento.removeTextChangedListener(oldListener);
TextWatcher watcher = new TextWatcher() {
double valor;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(atual)) {
edFaturamento.removeTextChangedListener(this);
String texto = s.toString().replaceAll("[.,]", "");
valor = Double.parseDouble("0" + texto);
String valorFormatado = decimalFormat.format(valor/100);
atual = valorFormatado;
edFaturamento.setText(valorFormatado);
edFaturamento.setSelection(valorFormatado.length());
edFaturamento.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
edFaturamento.setTag(watcher);
edFaturamento.addTextChangedListener(watcher);
return view;
}
public ArrayList<FaturamentoMes> getLista() {
return lista;
}
#Override
public int getCount() {
return this.lista.size();
}
#Nullable
#Override
public FaturamentoMes getItem(int position) {
return this.lista.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
}
I have cardviews, and I need to change some of them. The problem is that when I have more than one cardview I click on one and it changes the data of the last cardview that I have and not of exactly that I clicked
#RequiresApi(api = Build.VERSION_CODES.N)
public class ReagendarAdapter extends BaseAdapter {
private static final String TAG = "vania";
private List<Visita> visitaList;
private Context context;
private Calendar dateTime = Calendar.getInstance();
private String dataAntiga;
private Date novaDataInicio = new Date();
private Date novaDataFinal = new Date();
private ViewHolder holder;
public ReagendarAdapter(List<Visita> visitaList, Context context) {
this.visitaList = visitaList;
this.context = context;
}
#Override
public int getCount() {
return visitaList.size();
}
#Override
public Visita getItem(int position) {
return visitaList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
#BindView(R.id.txtCliente)
TextView txtCliente;
#BindView(R.id.txtAtividade)
TextView txtAtividade;
#BindView(R.id.txtData)
TextView txtData;
#BindView(R.id.txtDuracao)
TextView txtDuracao;
#BindView(R.id.txtNovaData)
TextView txtNovaData;
#BindView(R.id.llData)
LinearLayout llData;
#BindView(R.id.llMudarDuracao)
LinearLayout llMudarDuracao;
#BindView(R.id.btnReagendr)
Button btnReagendr;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
#SuppressLint({"SimpleDateFormat", "SetTextI18n"})
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert inflater != null;
row = inflater.inflate(R.layout.reagendar_row, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Visita visita = visitaList.get(position);
assert visita != null;
Date dataInicio = new Date(visita.getDtinicio() + (3 * 3600 * 1000));
if (visita.getNome() != null)
holder.txtCliente.setText(visita.getNome());
if (visita.getDtinicio() != null) {
dataAntiga = " " + new SimpleDateFormat("dd/MM 'às' HH:mm").format(dataInicio);
holder.txtData.setText(dataAntiga);
}
if (visita.getTipoevento() != null) {
String atividade = getPrefString(visita.getTipoevento().toString(), context);
holder.txtAtividade.setText(atividade);
}
holder.txtDuracao.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!dataAntiga.equalsIgnoreCase(String.valueOf(holder.txtData))){
holder.btnReagendr.setBackgroundColor(context.getResources().getColor(R.color.BrightBlue));
holder.btnReagendr.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.llData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDate();
}
});
holder.llMudarDuracao.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDate();
}
});
holder.btnReagendr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
visita.setStatusVisita("reagendada");
visita.setDataInicio(novaDataInicio);
visita.setDataFim(novaDataFinal);
updateAtvidade(context, visita);
}
});
return row;
}
private void updateDate() {
new DatePickerDialog(context, R.style.Picker, d, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH), dateTime.get(Calendar.DAY_OF_MONTH)).show();
}
private void updateTime() {
new TimePickerDialog(context, R.style.Picker, t, dateTime.get(Calendar.HOUR_OF_DAY), dateTime.get(Calendar.MINUTE), true).show();
}
private void updateHour() {
NumberPicker numberPicker = new NumberPicker(context);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#SuppressLint("SetTextI18n")
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
if (newVal != 1)
holder.txtDuracao.setText(" " + newVal + " horas");
else
holder.txtDuracao.setText(" " + newVal + " hora");
holder.txtNovaData.setText("Nova Data: ");
holder.llMudarDuracao.setVisibility(View.VISIBLE);
holder.txtDuracao.setTextColor(ColorStateList.valueOf(context.getResources().getColor(R.color.BrightBlue)));
novaDataFinal = new Date(novaDataInicio.getTime() + ( newVal* 3600 * 1000));
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(numberPicker);
builder
.setTitle("Duração")
.setIcon(R.drawable.ic_action_timer)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
private DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
dateTime.set(Calendar.YEAR, year);
dateTime.set(Calendar.MONTH, month);
dateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateTime();
}
};
private TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateTime.set(Calendar.MINUTE, minute);
novaDataInicio = dateTime.getTime();
atualizaString(holder.txtData);
updateHour();
}
};
#SuppressLint("SimpleDateFormat")
private void atualizaString(TextView textView) {
textView.setText(String.format(" %s", new SimpleDateFormat("dd/MM 'às' HH:mm").format(dateTime.getTime())));
textView.setTextColor(ColorStateList.valueOf(context.getResources().getColor(R.color.BrightBlue)));
}
I can only access the textview by creating the viewHolder in the class, I do not know how to do otherwise.
When I created methods to access within the getview the cardviews did not update at the same time, only after clicking them again
I have three edittext on one layout. When it's empty, then I remove the right drawable. When it isn't empty, I added the drawable. When you click to drawable, I clear the edittext.
When I clicked to rightdrawable, the cursor was stuck, and underline stay colored. Rarely I have a 2-3 cursor. Why?? What I do bad?
BAD:
GOOD:
The Layout:
<EditText
android:id="#+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#mipmap/ic_launcher"/>
<EditText
android:id="#+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#mipmap/ic_launcher"/>
<EditText
android:id="#+id/et3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#mipmap/ic_launcher"/>
The MainActivity
public class MainActivity extends AppCompatActivity {
private DrawableState etstate1;
private DrawableState etstate2;
private DrawableState etstate3;
private EditText et2;
private EditText et1;
private EditText et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
et3 = (EditText)findViewById(R.id.et3);
etstate1 = new DrawableState(et1);
etstate2 = new DrawableState(et2);
etstate3 = new DrawableState(et3);
et1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (DrawableClick.isDrawableClick(motionEvent, et1, DRAWABLE_RIGHT)) {
et1.setText("");
etstate1.refreshDrawable();
return true;
}
return false;
}
});
et2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (DrawableClick.isDrawableClick(motionEvent, et2, DRAWABLE_RIGHT)) {
et2.setText("");
etstate2.refreshDrawable();
return true;
}
return false;
}
});
et3.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (DrawableClick.isDrawableClick(motionEvent, et3, DRAWABLE_RIGHT)) {
et3.setText("");
etstate3.refreshDrawable();
return true;
}
return false;
}
});
et1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
etstate1.refreshDrawable();
}
});
et2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
etstate2.refreshDrawable();
}
});
et3.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
etstate3.refreshDrawable();
}
});
}
}
Helper classes:
public class DrawableClick {
public static boolean isDrawableClick(MotionEvent event, EditText editText, DrawablePositions drawablePosition) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (editText.getCompoundDrawables()[drawablePosition.position] != null && event.getX() >= (editText.getRight() - editText.getLeft() - editText.getCompoundDrawables()[drawablePosition.position].getBounds().width())) {
return true;
}
}
return false;
}
public enum DrawablePositions {
DRAWABLE_LEFT(0),
DRAWABLE_TOP(1),
DRAWABLE_RIGHT(2),
DRAWABLE_BOTTOM(3);
private int position;
DrawablePositions(int pos) {
this.position = pos;
}
}
}
Next:
public class DrawableState {
private EditText editText;
private Drawable[] editTextDrawables;
public DrawableState(EditText editText) {
this.editText = editText;
saveDrawableState();
refreshDrawable();
}
public void saveDrawableState() {
this.editTextDrawables = editText.getCompoundDrawables();
}
public void refreshDrawable() {
if (editText.getText().toString().equals("")) {
editText.setCompoundDrawables(null, null, null, null);
editText.clearFocus();
} else {
if (editTextDrawables != null) {
editText.setCompoundDrawables(editTextDrawables[0], editTextDrawables[1], editTextDrawables[2], editTextDrawables[3]);
}
}
}
I found the solution.
Change it
if (DrawableClick.isDrawableClick(motionEvent, et3, DRAWABLE_RIGHT)) {
...
return true;
}
return false;
To:
if (DrawableClick.isDrawableClick(motionEvent, et3, DRAWABLE_RIGHT)) {
...
motionEvent.setAction(MotionEvent.ACTION_CANCEL);
}
return false;
I have listview,its getting data from website and displaying in an Listview,I want to use search function,in my listview i am having title and content.I want to search using content alone thats enough.How to use search function for my listview.
It shows problem in this line List newListTwo=new List(); the error is Cannot instantiate the type List
Myactivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
String selection = myFilter.getText().toString().toLowerCase();
List<Application> newListTwo=new List<Application>();
int textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < items.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(items.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(items.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ApplicationAdapter(MainActivity.this, newListTwo);
setListAdapter(adapter);
}
private void setListAdapter(ApplicationAdapter adapter) {
// TODO Auto-generated method stub
}
});
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
For my code how to use the search function,i have my applicaton.java and applicationadapter.java also
Applicationadapter.java
#SuppressLint("NewApi")
public class ApplicationAdapter extends ArrayAdapter<Application> implements
TextToSpeech.OnInitListener{
private List<Application> items;
private LayoutInflater inflator;
private MainActivity activity;
private ProgressDialog dialog;
public TextToSpeech tts;
public ImageButton btnaudioprayer;
public TextView text1;
ArrayAdapter<String> adapter;
public ApplicationAdapter(MainActivity context, List<Application> items){
super(context, R.layout.activity_row, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
activity=context;
}
#Override
public int getCount(){
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
tts = new TextToSpeech(activity, ApplicationAdapter.this);
//View v = convertView;
if ( convertView == null ){
convertView = inflator.inflate(R.layout.activity_row, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text2);
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
holder.count = (TextView) convertView.findViewById(R.id.count);
holder.pray = (Button) convertView.findViewById(R.id.pray);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.btnaudioprayer = (ImageButton) convertView.findViewById(R.id.btnaudioprayer);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();
items.get(getPosition).setSelected(view.isChecked());
}
});
holder.pray.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int getPosition= (Integer)v.getTag();
StringBuffer sb1 = new StringBuffer();
sb1.append("ID :");
sb1.append(Html.fromHtml(""+items.get(getPosition).getId()));
sb1.append("\n");
activity.praydata(items.get(getPosition).getId());
//activity.showAlertView(sb1.toString().trim());
//activity.praydata(Integer.parseInt(sb1.toString().trim()));
}
});
holder.btnaudioprayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
View parent = (View)V.getParent();
ViewHolder vh = (ViewHolder)parent.getTag();
TextView tv = vh.text1;
speakOut(tv.getText().toString());
}
});
Application app = items.get(position);
holder.chk.setTag(position);
holder.pray.setTag(position);
holder.text2.setText(Html.fromHtml(app.getTitle()));
holder.text1.setText(Html.fromHtml(app.getContent()));
holder.count.setText(app.getCount()+"");
holder.chk.setChecked(app.isSelected());
return convertView;
}
static class ViewHolder {
public TextView text2;
public TextView text1;
public TextView count;
public CheckBox chk;
public Button pray;
public ImageButton btnaudioprayer;
private TextToSpeech tts;
}
//return convertView;
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Use addTextChangeListener to show list according to the content:-
searchContentEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
selection= searchContentEditText.getText().toString().toLowerCase();
List newListTwo=new ArrayList();
textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < contactList.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(firstList.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(firstList.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ContactListAdapter(MyActivity.this, newListTwo);
setListAdapter(adapter);
}
});
You need to implement your MyActivity.java class with TextWatcher.
public class MyActivity extends Activity implements TextWatcher {
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(this);
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Group[] group_array = null;
this.array_sort = new ArrayList<Group>();
try {
if(user != null) {
group_array = this.user.getUser_groups().getData();
}
int textlength = this.search_bar.getText().length();
for(int i=0; i<group_array.length; i++) {
if(textlength <= group_array[i].getGroup_name().length()) {
if(((String) group_array[i].getGroup_name().subSequence(0, textlength))
.equalsIgnoreCase(this.search_bar.getText().toString()))
{
this.array_sort.add(group_array[i]);
}
}
}
if(this.array_sort.size() > 0) {
Group[] groups = new Group[this.array_sort.size()];
FetchGroups.this.group_adapter = new GroupAdapter(FetchGroups.this,R.layout.row_fetch_groups,
android.R.layout.simple_list_item_1, this.array_sort.toArray(groups));
FetchGroups.this.groups_list.setAdapter(group_adapter);
}
} catch(Exception e) {
e.printStackTrace();
}
}