I want to convert choosen element to Integer. When it's done I want to add a random number between 1-20 to choosen Integer. Than show up that number in Toast.
To convert a value coming from a TextView to an integer, you just need to use the following code:
EditText tViewNum = (EditText) rootView.findViewById(R.id.number);
String strWord = tViewNum.getText().toString();
Random r = new Random();
int i1 = r.nextInt(21 - 1) + 20;
String Randomiser = strWord + " " + il; //the +" "+ is used to add a space between the word and the random number.
Toast.makeText(MainActivity.this, Randomiser + "//any other text you wish to include", Toast.LENGTH_SHORT).show();
Note that the random number given here is between 1 (inclusive) and 20 (inclusive).
use a widget forAutoCompleteTextView.
"CustomAutoCompleteTextView"
public class CustomAutoCompleteTextView extends AutoCompleteTextView {
public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void performFiltering(final CharSequence text, final int keyCode) {
// String filterText = "";
super.performFiltering(text, keyCode);
}
/**
* After a selection, capture the new value and append to the existing
* text
*/
#Override
protected void replaceText(final CharSequence text) {
super.replaceText(text);
}
}
Your Xml will be like this:[Depend where you add your widget ]
<com.example.widget.CustomAutoCompleteTextView
android:id="#+id/sent_message_to"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_margin="10dip"
android:layout_weight="1"
android:imeOptions="actionSend"
android:hint="name"
android:gravity="left|center"
android:padding="10dip"
android:textColor="#color/green"
android:textSize="18dp"
android:visibility="visible"
android:selectAllOnFocus="true"
android:inputType="textPersonName"
android:completionThreshold="3"
/>
Main class
you can set adapter for list value or declare array
private AutoCompleteAdapter mAutoCompleteAdapter;
private ArrayList<String> mArray = new ArrayList<String>();
private CustomAutoCompleteTextView mAutoFillTextView;
.....
mAutoFillTextView = mViewUtils.createAutoFillTextView(view.findViewById(R.id.sent_message_to), false);
mAutoCompleteAdapter = new AutoCompleteAdapter(getActivity(), mArray);
mAutoFillTextView.setAdapter(mAutoCompleteAdapter);
and
mAutoFillTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
try {
mArray.clear();
String string = s.toString().trim();
if (mAutoFillTextView.getThreshold() <= string.length() && mAllowRequest) {
//GET DATA TO LIST
}
} catch (NullPointerException ignored) {
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I'm creating a music player. This class among other things is suppose to add new songs to the playlist.
A new window pops up with available songs and the checked songs get added. Songs can be filtered and the selected rows are to change the color when the checkbox is checked. The filtering works and everything is being added the way it's suppose to but...
The problem is that when I check a song/some songs and then click on the search filter and the soft keyboard pops up the color of the selected rows changes to the default color, (the the song is still checked and can be added to the Playlist). When songs are checked and I hide the keyboard the same thing happens.
The other issue is that when the list gets filtered the color of the row previously selected goes away as well when the search box is cleared, the songs remain schecked though.
And I don't understand how and why that happens and therefore how to fix this.
Anyone has any ideas, please?
I think I don't understand how updating after filtering works and what notifyDataSetChanged() does exactly.
Here's the adapter code :
public class MyTrackAdapter extends ArrayAdapter<File>
{
private final Activity context;
private ArrayList<File> album, temp;
private ArrayList<File> piosenki;
public MyTrackAdapter(Activity context, ArrayList<File> album)
{
super(context, R.layout.adapter_traki, album);
this.context = context;
this.temp = new ArrayList<File>(album);
this.album = album;
this.piosenki=new ArrayList<File>();
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
final View rowView = inflater.inflate(R.layout.adapter_traki, null,true);
final CheckBox cb_plus = (CheckBox) rowView.findViewById(R.id.add);
final int position1=position;
final TextView txt = (TextView) rowView.findViewById(R.id.list_text);
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
txt.setText(album.get(position1).getName().toString().replace(".mp3",""));
cb_plus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (cb_plus.isChecked())
{
cb_plus.setBackgroundResource(R.drawable.x2);
txt.setTextColor(context.getResources().getColor(R.color.bdcolor));
rowView.setBackgroundResource(R.color.acolor);
piosenki.add(album.get(position1));
}
else
{
cb_plus.setBackgroundResource(R.drawable.plus);
txt.setTextColor(context.getResources().getColor(R.color.gcolor));
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
piosenki.remove(album.get(position1));
}
}
});
return rowView;
}
public void showTost(String s)
{
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
public ArrayList<File> getpiosenki()
{
return piosenki;
}
public Filter getFilter()
{
return filtr;
}
private Filter filtr = new Filter()
{
protected FilterResults performFiltering(CharSequence s)
{
FilterResults r = new FilterResults();
ArrayList<File> f = new ArrayList<File>();
if(s==null || s.length()==0) f.addAll(temp);
else
{
String ss=s.toString().toLowerCase().trim();
for(File ff : temp) if(ff.getName().replace(".mp3", "").toLowerCase().contains(ss)) f.add(ff);
}
r.values=f;
r.count=f.size();
return r;
}
protected void publishResults(CharSequence s, FilterResults r)
{
album.clear();
album.addAll((ArrayList)r.values);
notifyDataSetChanged();
}
};
}
And the Playlist class :
public class Playlist extends Activity implements TextWatcher
{
int where;
long pos;
String pllist;
ArrayList<String> lstp, lsts;
ArrayList<Long> lsti;
ArrayList<Integer> lstx;
DBHandler db;
private TextView txt1, txt2;
ImageView pic;
private ListView lv_traki;
ListView lv_traki2add;
PopupWindow pw;
View popupv;
TextView etext;
MyTrackAdapter tadapter;
ImageView add2list;
ArrayList <File> piosenki, toadd;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
db = new DBHandler(getApplicationContext());
Intent tnt = getIntent();
Bundle bn = tnt.getExtras();
lstp = (ArrayList) bn.getParcelableArrayList("path");
lsts = (ArrayList) bn.getParcelableArrayList("song");
lsti = (ArrayList) bn.getParcelableArrayList("indx");
lstx = (ArrayList) bn.getParcelableArrayList("pause");
pos = bn.getLong("pos", 0);
where = bn.getInt("skad", 0);
pllist = bn.getString("album");
piosenki = (ArrayList) bn.getParcelableArrayList("full");
setData(0, lstp.size());
songlist();
lv_traki.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l)
{
Intent it;
lstp.clear();
lsti.clear();
lsts.clear();
lstx.clear();
db.gett1path(pos, lstp);
db.gett1song(pos, lsts);
db.gett1pause(pos, lstx);
db.gett1id(pos, lsti);
it=new Intent(getApplicationContext(), Player.class);
it.putExtra("path", lstp).putExtra("nazwa", lsts).putExtra("pause", lstx).putExtra("pos",i).putExtra("skad",4);
startActivity(it);
}
});
if(where==5) lv_traki.performItemClick(lv_traki.getAdapter().getView(0, null, null), 0, lv_traki.getAdapter().getItemId(0));
add2list = (ImageView) findViewById(R.id.btn_addtoplay);
toadd = new ArrayList<File>();
add2list.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
popupv = ((LayoutInflater) getApplicationContext().getSystemService("layout_inflater")).inflate(R.layout.popup_addtolist, null);
ImageView btn01 = (ImageView) popupv.findViewById(R.id.btn_addtoplay);
FrameLayout fl = (FrameLayout) findViewById(R.id.frameLayout1);
etext = (EditText) popupv.findViewById(R.id.etext);
etext.addTextChangedListener(Playlist.this);
lv_traki2add = (ListView) popupv.findViewById(R.id.lst_traki2add);
tadapter = new MyTrackAdapter(Playlist.this, piosenki);
lv_traki2add.setAdapter(tadapter);
toadd=tadapter.getpiosenki();
btn01.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(toadd.size()>0)
{
for (File addt1 : toadd)
{
db.addt1(pos, addt1);
}
lstp.clear();
lsts.clear();
lstx.clear();
lsti.clear();
db.gett1path(pos, lstp);
db.gett1song(pos, lsts);
db.gett1pause(pos, lstx);
db.gett1id(pos, lsti);
lv_traki.setAdapter(null);
setData(0, lstp.size());
MyPlaylistAdapter adapter=new MyPlaylistAdapter(Playlist.this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2);
lv_traki.setAdapter(adapter);
for(int x=0; x<lv_traki2add.getChildCount(); x++)
{
CheckBox cb = lv_traki2add.getChildAt(x).findViewById(R.id.add);
cb.setChecked(false);
}
pw.dismiss();
showTost("Songs Added");
}
else pw.dismiss();
}
});
pw = new PopupWindow(popupv, -1, -1, true);
pw.showAtLocation(fl, 17, 0, 0);
}
});
}
private void songlist()
{
lv_traki = (ListView) findViewById(R.id.lst_traki);
MyPlaylistAdapter adapter=new MyPlaylistAdapter(this, lsts, lstp, lsti, lstx, pos, pllist, lv_traki, txt2);
lv_traki.setAdapter(adapter);
}
public void setData(int z, int size)
{
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
MediaMetadataRetriever tmp = new MediaMetadataRetriever();
mmr.setDataSource(lstp.get(z));
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
pic = (ImageView) findViewById(R.id.img_bg);
int tmax = 0;
for(int i=0;i<size;i++)
{
tmp.setDataSource(lstp.get(i));
tmax+=Integer.parseInt(tmp.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
tmax+=lstx.get(i)*1000;
}
txt1.setText(pllist);
if (size>1) txt2.setText(size+" songs; "+mili_t(tmax));
else txt2.setText("1 song; "+mili_t(tmax));
Bitmap bm;
Drawable d;
byte [] img = mmr.getEmbeddedPicture();
if(img!=null)
{
bm = BitmapFactory.decodeByteArray(img, 0, img.length);
d = new BitmapDrawable(getResources(), bm);
pic.setBackground(d);
}
else
{
pic.setBackgroundResource(R.drawable.no_image);
pic.getLayoutParams().height = 400;
pic.getLayoutParams().width = 400;
pic.setScaleType(ScaleType.CENTER_INSIDE);
}
}
public String mili_t(int t)
{
int s = (int) (t / 1000) % 60 ;
int m = (int) ((t / (1000*60)) % 60);
int h = (int) ((t / (1000*60*60)) % 24);
String dt="", dh, ds, dm;
if(h>0)
{
dh=Integer.toString(h);
if(h<10) dh="0"+dh;
dt=dt+dh+":";
}
if(m>=0)
{
dm=Integer.toString(m);
if(m<10) dm="0"+dm;
dt=dt+dm+":";
}
if(s>=0)
{
ds=Integer.toString(s);
if(s<10) ds="0"+ds;
dt=dt+ds;
}
return dt;
}
public void showTost(String s)
{
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
tadapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
}
And the xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popupwrap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/bdcolor">
<RelativeLayout
android:id="#+id/popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/bdcolor">
<EditText
android:id="#+id/etext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/bbcolor"
android:hint="SEARCH FILTER"
android:background="#drawable/etext"
android:textSize="24sp"
android:textCursorDrawable="#drawable/cursor"
android:textColor="#color/gcolor"
android:inputType="text"
android:layout_marginLeft="10dp"
android:layout_marginRight="80dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<ImageView
android:id="#+id/btn_addtoplay"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:src="#drawable/check1"
android:clickable="true"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_centerVertical="true"/>
</RelativeLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lst_traki2add">
</ListView>
</LinearLayout>
The problem is that you are relying on the Checkbox view in each row to maintain the selection state for that row. You will also see strange behavior if you have a long list of songs, select some, and then scroll. Both of these problems are because ListView will recycle the views that are used to render the songs that are currently displayed rather than creating a new set of views for every row.
To solve this problem, you need to maintain the selection state yourself. You can do this with a bool[] or List<Boolean> that stores a flag for every song in your current data. Use this to set the background color and checkbox state rather than relying on the checkbox state to set the background color.
reason is simple - you have OnCheckedChangeListener which fires after every (un)check and is changing background. Everytime you call notifyDataSetChanged() whole list will be redrawn, so background color will be again set with if(position1 %2 == 1) condition in getView method, but listener won't fire again. check out his code with manual listener call
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (cb_plus.isChecked())
{
cb_plus.setBackgroundResource(R.drawable.x2);
txt.setTextColor(context.getResources().getColor(R.color.bdcolor));
rowView.setBackgroundResource(R.color.acolor);
if(piosenki.get(album.get(position1)) != null) // won't duplicate
piosenki.add(album.get(position1));
}
else
{
cb_plus.setBackgroundResource(R.drawable.plus);
txt.setTextColor(context.getResources().getColor(R.color.gcolor));
if(position1 %2 == 1) rowView.setBackgroundResource(R.color.bbcolor);
else rowView.setBackgroundResource(R.color.bpcolor);
piosenki.remove(album.get(position1));
}
}
}
boolean isAdded = ...;
cb_plus.setChecked(isAdded);
cb_plus.setOnCheckedChangeListener(listener); // set listener after setting (un)checked
listener.onCheckedChanged(cb_plus, isAdded); // manual call
isAdded is your condition for CheckBox checked or not, problably piosenki.contains(album.get(position1)); or piosenki.get(album.get(position1)) != null;. you can also get rid of few duplicated lines from getView method, like those with background or textcolor setting - these will be called inside manual listener call
PS. also change piosenki to songs ;)
I have an AutoCompleteTextView, and depending from the changes in it, it shows the dropdown list with the data from server. Via listener after changing every symbol I make request to the server and take some list.
After that I show that list in AutoCompleteTextView, in code I do it by this way:
List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i).getString("title"));
}
String[] cities = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
Problem is it oftenly shows only the first element of the list, and after long click it shows the full list. I don understand why its happening.
Sorry for the bad eng, thanks in advance! Also you could check the rest of the code below:
xml part:
<AutoCompleteTextView
android:id="#+id/from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp"
android:background="#drawable/td_inp"
android:hint="Откуда"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:textColor="#000"
android:textColorHint="#757575" />
AutoCompleteTextView and its listener in onCreate
tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(s.length() >= 2) load_city(ssid, s.toString(),tCityFrom);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
I assume you want to show AutoComplete suggestions according to what user types. You have to load data from server onTextChanged():
tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.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) {
if(s.length() >= 2)
load_city(ssid, s.toString(),tCityFrom);
}
});
Then declare ArrayList and Adapter globally:
List<String> list;
ArrayAdapter<String> adapter;
In onCreate():
list = new ArrayList<String>();
adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
Replace your first code snippet of load_city() with below code :
list.clear();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();
Hope this helps.
I have four EditText boxes that together make up a value. Each box should contain 1 number. When I enter a number into one box the focus should move to the next box. I have "faked" a link between the boxes by modifying the focus when the text is changed. The following code works but I want to allow for the user to paste in values that will then be split across the EditText boxes. So if I paste "123" in box[0], box[0] should contain "1" and box[1] should contain "2" etc. I attempted to add android:maxLength="1" to the XML but when I attempt to paste content, the maxLength validation removes all but the first character.
What is the best way to split the contents of a paste across the 4 EditText boxes?
EnterNumberLayout.java
public class EnterNumberLayout extends LinearLayout {
EditText[] textBoxes;
public static final int NUMBER_OF_ENTRIES = 4;
public EnterNumberLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOrientation(HORIZONTAL);
textBoxes = new EditText[NUMBER_OF_ENTRIES];
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
for (int i = 0; i < NUMBER_OF_ENTRIES; i++){
EditText et = (EditText) inflater.inflate(R.layout.number_box, null);
//et.setOnKeyListener(new BackspaceKeyListener(et));
et.addTextChangedListener(new MoveFocusWatcher(et));
et.setTag(i);
textBoxes[i] = et;
this.addView(et, i);
}
}
private class MoveFocusWatcher implements TextWatcher {
private View view;
public MoveFocusWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((int) this.view.getTag() < NUMBER_OF_ENTRIES - 1) {
(textBoxes[(int) this.view.getTag() + 1]).requestFocus();
}
}
public void afterTextChanged(Editable s) {}
}
}
number_box.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number|none"
android:ellipsize="start"
android:gravity="center_horizontal|center_vertical"
android:imeOptions="actionNext"/>
There are probably a few ways to do this, but I'd probably remove the text limit of 1 on the edit text and manage the length with a text watcher.
Here, if text is pasted into the first edit1 then the text watcher will split the values up into the other edit text fields. You need to be careful when changing text in the afterTextChanged callback since the change will initiate another call to the method. Since the text length in edit1 is only one after our processing, the next callback does nothing.
public class TextGroup extends LinearLayout {
EditText edit0;
EditText edit1;
EditText edit2;
EditText edit3;
public TextGroup(Context context, AttributeSet attrs) {
super(context);
View view = LayoutInflater.from(context).inflate(R.layout.edit_text_special, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
edit0 = (EditText) view.findViewById(R.id.edit_text0);
edit1 = (EditText) view.findViewById(R.id.edit_text1);
edit2 = (EditText) view.findViewById(R.id.edit_text2);
edit3 = (EditText) view.findViewById(R.id.edit_text3);
edit1.addTextChangedListener(watcher);
this.addView(view, lp);
}
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable editable) {
if ( edit1.getText().length() >= 3) {
edit3.setText(String.valueOf(edit1.getText().toString().charAt(2)));
}
if ( edit1.getText().length() >= 2) {
edit2.setText(String.valueOf(edit1.getText().toString().charAt(1)));
edit1.setText(String.valueOf(edit1.getText().toString().charAt(0)));
}
}
};
}
I have a listView with about 30 items in it and have added a search function to it via an editText. When I type 'a' in the textfield everything that starts with an 'a' shows up on the list but when I type another letter the list disappears even tho the list contains an item with 'a' + the other letter i typed.
Another thing that confuses me is that there is an item in the list called IWU Trading and thats the only item I can search for, means that if I type 'I' + 'W' the item shows up in the listView. But if I type 'a' + 'r' an item that is named 'art' dosent show up.
My question(s).
How can I do to make this search function work?
Why does it act like it does?
My XML
<EditText
android:id="#+id/searchEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/selectCustomerTextView"
android:layout_marginTop="20dp"
android:hint="#string/typeToSearch"
android:ems="10"
android:imeOptions="actionDone"
android:inputType="textNoSuggestions"/>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/nextButton"
android:layout_alignParentLeft="true"
android:layout_below="#+id/searchEditText"
android:choiceMode="singleChoice"
android:dividerHeight="5dp" >
</ListView>
My code:
private ArrayAdapter<Customer> _oldAdapter = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.activity_customer_pick);
EditText searchText = (EditText) findViewById(R.id.searchEditText);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
searchText.addTextChangedListener(filterTextWatcher);
_oldAdapter = _phoneDAL.BindValues(this);
listView.setAdapter(_oldAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String s = _oldAdapter.getItem(arg2).toString();
_listViewPostion = arg2;
Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show();
}
});
}
The search method:
private TextWatcher filterTextWatcher = 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) {
ArrayAdapter<Customer> _adapter = new ArrayAdapter<Customer>(CustomerPick.this, android.R.layout.simple_list_item_single_choice, new ArrayList<Customer>());
ListView listView = (ListView) findViewById(R.id.list_view);
int textLength = s.length();
if(textLength == 0){
listView.setAdapter(_oldAdapter);
return;
}
for (int i = 0; i < listView.getAdapter().getCount(); i++)
{
String word = _oldAdapter.getItem(i).getCustName().toLowerCase();
if (textLength <= word.length())
{
if(s.toString().equalsIgnoreCase(word.substring(0, textLength)))
{
_adapter.add(_oldAdapter.getItem(i));
}
}
}
listView.setAdapter(_adapter);
}
};
}
My CustomerClass (private ArrayAdapter _oldAdapter = null;)
public class Customer {
private final int _custNumber;
private final String _custName;
public Customer(int custNumber, String custName){
_custNumber = custNumber;
_custName = custName;
}
public int getCustNumber() {
return _custNumber;
}
public String getCustName() {
return _custName;
}
#Override
public String toString(){
return _custName;
}
}
Solved the problem by adding:
ListView listView = (ListView) findViewById(R.id.list_view);
((Filterable) listView.getAdapter()).getFilter().filter(s);
into the afterTextChanged method of the TextWatcher(after reading Luksprog's comment).
In my Appliaction I use a CursorAdapter. This displays a list, which is part of a RelativeLayout. This List includes several elements(TextView, Button, EditText). The EditText does not normally appear on the screen.The problem: I import any data to a EditText and scroll the screen. In this moment I see the imported data in another EditText. OR:
Another case. There are 3 EditText. I use the virtual Keyboard (For example use the second editText). I get in the data to the Edit Text. Push the Back Button. And the data goes to the Edit Text below. (So the data go to the third Edit Text)
Here is the CursorAdapter Code:
class OOSListadapter extends CursorAdapter{
OOSListadapter(Cursor c){
super(OOS.this,c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
OOSRow newRow = (OOSRow)view.getTag();
newRow.populateRow(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.oos_row, parent, false);
OOSRow newRow = new OOSRow(row);
row.setTag(newRow);
return (row);
}
}
And here is one row from my application list.
class OOSRow {
private TextView row_Action = null;;
private TextView row_Must = null;;
private TextView row_Lack = null;;
private TextView row_itemName = null;;
private EditText row_price = null;;
private Button row_detail = null;
private View row = null;
OOSRow (View row){
this.row = row;
row_Action = (TextView)row.findViewById(R.id.oos_row_SignalA);
row_Must = (TextView)row.findViewById(R.id.oos_row_SignalK);
row_Lack = (TextView)row.findViewById(R.id.oos_row_SignalO);
row_itemName = (TextView)row.findViewById(R.id.oos_row_itemLabel);
row_price = (EditText)row.findViewById(R.id.oos_row_EditText);
row_detail = (Button)row.findViewById(R.id.oos_row_detailButton);
}
void populateRow (Cursor c){
Cursor specCursor = dbLoc.Query("SELECT PRICE, LACK, ORDERED FROM ORDERED WHERE ITEMID='"+ c.getString(1) +"'", null);
specCursor.moveToFirst();
row_itemName.setText(c.getString(2));
row_itemName.setContentDescription(c.getString(1));
if (specCursor.getString(1).toString().equals("Y")){
row_itemName.setBackgroundColor(Color.parseColor("#FF0000"));
row_itemName.setTextColor(Color.parseColor("#FFFFFF"));
}else{
row_itemName.setBackgroundColor(Color.parseColor("#000000"));
row_itemName.setTextColor(Color.parseColor("#FFFFFF"));
}
row_itemName.setOnClickListener(SelectedLackItem);
if (c.getString(5).toString().equals("I")){
row_Action.setTextColor(Color.parseColor("#000000"));
row_Action.setBackgroundColor(Color.parseColor("#FF0000"));
}
else{
row_Action.setTextColor(Color.parseColor("#FFFFFF"));
row_Action.setBackgroundColor(Color.parseColor("#000000"));
}
if (c.getString(4).toString().equals("I")){
row_Must.setTextColor(Color.parseColor("#000000"));
row_Must.setBackgroundColor(Color.parseColor("#00FF00"));
}
else{
row_Must.setTextColor(Color.parseColor("#FFFFFF"));
row_Must.setBackgroundColor(Color.parseColor("#000000"));
}
specCursor = dbLoc.Query("SELECT LACK FROM LASTORDERED WHERE ITEMID='"+c.getString(1)+"' AND COMPANYID ='"+dbLoc.GetCompanyId()+"'", null);
if (specCursor.moveToFirst())
{
if (specCursor.getString(0).toString().equals("I")){
row_Lack.setTextColor(Color.parseColor("#000000"));
row_Lack.setBackgroundColor(Color.parseColor("#0000FF"));
}else{
row_Lack.setTextColor(Color.parseColor("#FFFFFF"));
row_Lack.setBackgroundColor(Color.parseColor("#000000"));
}
}
row_detail.setOnClickListener(OpenDetailScreenButton);
row_detail.setContentDescription(c.getString(1));
row_price.setContentDescription(c.getString(1));
row_price.setInputType(0);
/*row_price.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
row_price.setInputType(InputType.TYPE_CLASS_NUMBER);
}
#Override
public void afterTextChanged(Editable s) {
}
});*/
specCursor.close();
specCursor = null;
}
}
And some pictures:
After Back Button:
Any Idea?
I had a very similar problem. The following solution helped me:
<activity android:name= ".yourActivity" android:windowSoftInputMode="adjustPan"/>