Android Listview add item and subitem programmatically [duplicate] - android

I currently have a listview which contains a couple of strings. These are called from a string array in strings.xml
<string name="app_name">Taxi Me</string>
<string-array name="taxi_array">
<item>Barrys Taxi</item>
<item>Boom Taxi</item>
</string-array>
What I was trying to do is create subitems for these so that i can show fields such as address and contact details etc. I made a customlistview a while back but cant work out how I can do it using the strings.xml file? Are there any particular tags I need to use so they show up in the list view?
Main Activity Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
final String[] address = getResources().getStringArray(R.array.taxi_add);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
for (int i = 0; i < taxi.length; i++) {
lv.add(new ListTaxi (taxi[i], address[i]));
}
/*lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_LONG).show();
}
});
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), Booking.class);
intent.putExtra("booking", taxi[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});

EDIT: Okay, just for kicks, I threw this together. It compiles and functions correctly, see if you can adapt it for your particular needs:
layout/taxi_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_address"
/>
</LinearLayout>
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
TaxiMain.java
package com.test.taxi;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feed_view, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
}
}
_____END EDIT_______
You'd probably be better off using a database for something like this, to keep the records tied together. If you're set on using arrays, one thing you could do is make a separate array for each item you need (e.g. taxi_array, taxi_address_array, taxi_phone_array) then make a Taxi object in your code:
class Taxi {
String taxiName;
String taxiAddress;
String taxiPhone;
public Taxi(String name, String address, String phone) {
taxiName = name;
taxiAddress = address;
taxiPhone = phone;
}
}
private List<Taxi> taxiList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray("taxi_array");
String[] taxiAddresses = getResources().getStringArray("taxi_address_array");
String[] taxiPhones = getResources().getStringArray("taxi_phone_array");
taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i], taxiPhones[i]));
}
}
(This is uncompiled code, some tweaks may be needed) But then you'll have a List of Taxi items, containing all of the compiled information from the different arrays. A database would still be a much better option (or even a CSV file with the data, in your assets).

I had same problem and I solved myself like this:
you can simply add subitem like this code and you don't need so much coding!!
<string name="app_name">Taxi Me</string>
<string-array name="taxi_array">
<item>
<item>Barrys Taxi</item>
<item>adress</item>
<item>contact</item>
<item>ANY THING...</item>
</item>
<item>
<item>Boom Taxi</item>
<item>adress</item>
<item>contact</item>
<item>ANY THING...</item>
</item>
</string-array>

Are you looking for some sort of nested Lists?
Have a look at ExpandableListView:
http://developer.android.com/reference/android/widget/ExpandableListView.html
and
http://mylifewithandroid.blogspot.com/2008/05/expandable-lists.html

Related

Hello, I have been working on android project where I need to send the selected String from listview to another activity

In my program I have fetched the data's from the server and view it in a listview. Then from those retrieved data in listview I have to select a string and that string will be passed on to another activity. My data's are retrieved and showed in listview but when I select an item(String) and try to send it to the next activity then instead of that string the package name is passed.
The layout code for retrieving and sending selected String is given below:
public class Doctors_layout extends Fragment implements
AdapterView.OnItemSelectedListener{
public final static String Message = "Sohan";
View myView;
Spinner spinner;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
String JSON_String;
ContactAdapter contactAdapter;
ListView listView;
Button button;
String send;
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.doctors_directory, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
spinner.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("Choose a City");
city.add("Chittagong");
city.add("Dhaka");
ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city);
aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// here we have to select medical name and intent viewDoctor page
Intent intent = new Intent(myContext, viewDoctor.class);
send = listView.getItemAtPosition(position).toString(); // doesn't retrieve the selected text, intead chooses package name
intent.putExtra(Message, send);
Toast.makeText(myContext, "Listview item "+send, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
return myView;
}
And my custom contact adapter class is given below:
package com.example.sohan.patient;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
View row;
ContactHolder contactHolder;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.MedicalName.setText(contacts.getMedicalName());
return row;
}
static class ContactHolder{
TextView MedicalName;
}
}
Try this, I hope it work...
send = ((TextView) view.findViewById(R.id.textView5)).getText().toString();
or
send = (String) parent.getItemAtPosition(position);
thanks..
send = listView.getItemAtPosition(position).toString();
you are sending a listView object and not actual string.
use:
send = yourListOfStrings.get(position)
UDP:
You are trying to create an adapter with onItemClick listener attacked to it:
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
right?
So you are suppose to fill(But I haven't found where you are doing this) this adapter with some data:
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
and you want to send a string from from the element of this list to another acitvity, right?
So you need to select an element of this list
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
send = updatedList.get(position).getYourString
inside onItemClickListener

ListView, Change each row with Array of color codes in Android

I'm trying to change the color of each row, I have 2 arrays. One has names of color, the other has color codes.
I have a ListView with Color names, the names are stored in an array of String.
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++)
lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
}
In arrays.xml:
<string-array name="listArray">
<item>aliceblue</item>
<item>antiquewhite</item>
<item>aquamarine</item>
<item>azure</item>
</string-array>
<string-array name="listValues">
<item>00f0f8ff</item>
<item>00faebd7</item>
<item>007fffd4</item>
<item>00f0ffff</item>
</string-array>
The app crashes at lv.getChildAt(i).setBackgroundColor(Color.parseColor(colourCodes[i]));
You must write your own custom ArrayAdapter.
First write a color class:
color.java:
public class color {
private String name;
private String color;
public color(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Then List item layout:
list_item_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Finally write custom adapter:
ColorListAdapter.java:
public class ColorListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<color> mColorList;
public ColorListAdapter(Activity activity, List<color> mColorList) {
mInflater = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
this.mColorList = mColorList;
}
#Override
public int getCount() {
return mColorList.size();
}
#Override
public Object getItem(int position) {
return mColorList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
// Get item_layout:
rowView = mInflater.inflate(R.layout.list_item_layout, null);
// Get TextView from item_layout:
TextView textView =
(TextView) rowView.findViewById(R.id.name);
// Get color and text from current position set TextView
color myColor = mColorList.get(position);
textView.setText(myColor.getName());
textView.setBackgroundColor(Color.parseColor(myColor.getColor()));
return rowView;
}
}
And these are MainActivity.java and activity_main.xml
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<color> colorList = new ArrayList<>();
// Add color objects:
colorList.add(new color("RED", "#FF0000"));
colorList.add(new color("GREEN", "#00FF00"));
colorList.add(new color("BLUE", "#0000FF"));
colorList.add(new color("MY BEST", "#013583"));
// Add list to your custom adapter
ListView myListView = (ListView) findViewById(R.id.liste);
ColorListAdapter mAdapter = new ColorListAdapter(this, colorList);
// Set Adapter
myListView.setAdapter(mAdapter);
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/liste"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</RelativeLayout>
Try this code
String[] colourNames;
String[] colourCodes;
protected void onCreate(Bundle savedInstanceState) {
colourNames = getResources().getStringArray(R.array.listArray);
colourCodes = getResources().getStringArray(R.array.listValues);
ListView lv = (ListView) findViewById(R.id.listView);
ArrayAdapter aa = new ArrayAdapter(this, R.layout.activity_listview, colourNames);
lv.setAdapter(aa);
for(int i=0; i<colourCodes.length; i++){
View wantedView = lv.getChildAt(i);
view.setBackgroundColor(Color.BLUE);
}
}
The problem is at this point ListView does not have any children. If you want to alter how children are displayed, you need create your own Adapter implementation and override getView(). You can simply subclass ArrayAdapter in this case and pass it your array of colors (or have it load the colors in the adapter, as I have done), then choose a color based on position.
Also, you might as well make your colors an integer array.
<integer-array name="listValues">
<item>0xfff0f8ff</item>
<item>0xfffaebd7</item>
<item>0xff7fffd4</item>
<item>0xfff0ffff</item>
</integer-array>
public class ColorsAdapter extends ArrayAdapter<String> {
private int[] mColors;
public ColorsAdapter(Context context) {
super(context, R.layout.activity_listview,
context.getResources().getStringArray(R.array.listArray));
mColors = context.getResources().getIntegerArray(R.array.listValues);
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int color = mColors[position % mColors.length]; // might as well be safe
view.setBackgroundColor(color);
return view;
}
}
I also highly recommend watching this video on how ListView works: The World of ListView. Also, nowadays people are moving toward RecyclerView instead; you don't have to do that necessarily, but either way this video should help you understand how these components behave.

Listview with Checkbox in android studio

I am trying to create a custom listview with a checkbox and a string list of "observations" retrieved from my sqlite database. The idea is that when I click on the "retrieve" button, all checked items are shown in a toast message.
I can populate the listview through my customadapter just fine, but it doesnt seem to recognise the status of each checkbox, as no toast messages are shown, regardless of whether they are checked.
Please can someone show me where I am going wrong?
Here is my custom listview xm that I have called list_o:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:id="#+id/obsgrid">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chkbx"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/obs"
android:layout_row="0"
android:layout_column="1" />
Here is my custom adapter:
class CustomAdObs extends ArrayAdapter<String> {
private String [] observation;
private Boolean [] checked;
private Context context;
public CustomAdObs(Context context, String[] observation) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater siteInflater = LayoutInflater.from(getContext());
View customView = siteInflater.inflate(R.layout.list_o, parent, false);
TextView observationTV = (TextView) customView.findViewById(R.id.obs);
CheckBox checkCB = (CheckBox) customView.findViewById(R.id.chkbx);
checkCB.setTag(Integer.valueOf(position));
observationTV.setText(observation[position]);
checkCB.setChecked(checked[position]);
return customView;
}
}
Finally here is my activity:
public class selobs extends Activity {
List< List<String> > listArray = new ArrayList< List<String> >();
List<String> array1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode. setThreadPolicy(policy);
setContentView(R.layout.activity_selobs);
final Button retrieve= (Button) findViewById(R.id.btnret);
final EditText txtob = (EditText) findViewById(R.id.editText23);
filladapter();
retrieve.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ListView obsListView = (ListView) findViewById(R.id.obsList);
View v;
for (int i = 0; i < obsListView.getCount(); i++) {
v = obsListView.getAdapter().getView(i, null, null);
CheckBox check = (CheckBox) v.findViewById(R.id.chkbx);
TextView obsItem = (TextView) v.findViewById(R.id.obs);
if (check.isChecked()) {
String p = obsItem.getText().toString();
Toast.makeText(selobs.this, p, Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void filladapter(){
myDBhandler1 dbHandler;
dbHandler = new myDBhandler1(selobs.this, null, null, 1);
listArray = dbHandler.databaseToStringObs();
List array1 = listArray.get(0);
String[] observ = (String[]) array1.toArray(new String[0]);
Boolean[] checked = new Boolean[0];
Arrays.fill(checked, Boolean.FALSE);
final ListAdapter ObsAdapter = new CustomAdObs(this, observ, checked);
final ListView obsListView = (ListView) findViewById(R.id.obsList);
obsListView.setAdapter(ObsAdapter);
obsListView.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(selobs.this, item, Toast.LENGTH_LONG).show();
TextView txtobs = (TextView) findViewById(R.id.editText23);
txtobs.setText(item);
}
}
);
}
}
your constructor
public CustomAdObs(Context context, String[] observation) {//here the Boolean[] checked ->is messing
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
so you replace it with this
public CustomAdObs(Context context, String[] observation, Boolean[] checked) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
why ?
because you call it like this
new CustomAdObs(this, observ, checked);
while you have just the 2 params in your constructor(Context context,String[] observation)

How to refresh the ListView in Drag-Sort ListView?

I have implement Drag-Sort ListView(DSLV) and LazyList together in my Project, I download the Demo LazyList and Drag-Sort ListView from github then integrate and modify as per my requirement ,
I use DSLV for drag and sort the items of ListView and LazyList for Displaying Image from URL,
i just implement "Basic usage playground" from DSLV for drag and sort,
I have implement search in TestBedDSLV.java, but the problem is that when I search the Content from the list, but i can't update the list, i have tried notifyDataSetChanged method but it not works, generally we create new adapter and pass it to listview like lv.setAdapter(adapter) , but here they just set ListAdapter, so we cant do lv.setAdapter(adapter)
TestBedDSLV.java
package com.mobeta.android.demodslv;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.Button;
import android.widget.EditText;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class TestBedDSLV extends FragmentActivity {
private int mNumHeaders = 0;
private int mNumFooters = 0;
private int mDragStartMode = DragSortController.ON_DOWN;
private boolean mRemoveEnabled = false;
private int mRemoveMode = DragSortController.FLING_RIGHT_REMOVE;
private boolean mSortEnabled = true;
private boolean mDragEnabled = true;
private String mTag = "dslvTag";
Button search;
EditText search_customer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_bed_main);
search = (Button) findViewById(R.id.btn_search);
search_customer = (EditText) findViewById(R.id.search_product);
search_customer.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// here is logic for refresh the list View
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.test_bed, getNewDslvFragment(), mTag).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mode_menu, menu);
return true;
}
private Fragment getNewDslvFragment() {
DSLVFragmentClicks f = DSLVFragmentClicks.newInstance(mNumHeaders,
mNumFooters);
f.removeMode = mRemoveMode;
f.removeEnabled = mRemoveEnabled;
f.dragStartMode = mDragStartMode;
f.sortEnabled = mSortEnabled;
f.dragEnabled = mDragEnabled;
return f;
}
}
DSLVFragmentClicks.java
package com.mobeta.android.demodslv;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.os.Bundle;
import android.widget.Toast;
public class DSLVFragmentClicks extends DSLVFragment {
public static DSLVFragmentClicks newInstance(int headers, int footers) {
DSLVFragmentClicks f = new DSLVFragmentClicks();
Bundle args = new Bundle();
args.putInt("headers", headers);
args.putInt("footers", footers);
f.setArguments(args);
return f;
}
AdapterView.OnItemLongClickListener mLongClickListener =
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Long-clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
return true;
}
};
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String message = String.format("Long-clicked item %d", arg2);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
DSLVFragment.java
package com.mobeta.android.demodslv;
import java.util.ArrayList;
import java.util.Arrays;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class DSLVFragment extends ListFragment {
ArrayAdapter<String> adapter;
private String[] array;
public static ArrayList<String> list;
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
String item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener() {
#Override
public void remove(int which) {
adapter.remove(adapter.getItem(which));
}
};
protected int getLayout() {
return R.layout.dslv_fragment_main;
}
/**
* Return list item layout resource passed to the ArrayAdapter.
*/
protected int getItemLayout() {
return R.layout.list_item_handle_right;
}
private DragSortListView mDslv;
private DragSortController mController;
public int dragStartMode = DragSortController.ON_DOWN;
public boolean removeEnabled = false;
public int removeMode = DragSortController.FLING_RIGHT_REMOVE;
public boolean sortEnabled = true;
public boolean dragEnabled = true;
public static DSLVFragment newInstance(int headers, int footers) {
DSLVFragment f = new DSLVFragment();
Bundle args = new Bundle();
args.putInt("headers", headers);
args.putInt("footers", footers);
f.setArguments(args);
return f;
}
public DragSortController getController() {
return mController;
}
/**
* Called from DSLVFragment.onActivityCreated(). Override to set a different
* adapter.
*/
public void setListAdapter() {
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
}
/**
* Called in onCreateView. Override this to provide a custom
* DragSortController.
*/
public DragSortController buildController(DragSortListView dslv) {
DragSortController controller = new DragSortController(dslv);
controller.setDragHandleId(R.id.drag_handle);
controller.setClickRemoveId(R.id.click_remove);
controller.setRemoveEnabled(removeEnabled);
controller.setSortEnabled(sortEnabled);
controller.setDragInitMode(dragStartMode);
controller.setRemoveMode(removeMode);
return controller;
}
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDslv = (DragSortListView) inflater.inflate(getLayout(), container,
false);
mController = buildController(mDslv);
mDslv.setFloatViewManager(mController);
mDslv.setOnTouchListener(mController);
mDslv.setDragEnabled(dragEnabled);
return mDslv;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDslv = (DragSortListView) getListView();
mDslv.setDropListener(onDrop);
mDslv.setRemoveListener(onRemove);
Bundle args = getArguments();
int headers = 0;
int footers = 0;
if (args != null) {
headers = args.getInt("headers", 0);
footers = args.getInt("footers", 0);
}
setListAdapter();
}
}
test_bed_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/search_lay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="horizontal" >
<EditText
android:id="#+id/search_product"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:layout_weight="1"
android:background="#drawable/search_back"
android:hint="Enter Firstname"
android:imeOptions="actionSearch"
android:inputType="text"
android:paddingBottom="2dp"
android:paddingLeft="5dp"
android:paddingTop="2dp"
android:visibility="visible" />
<Button
android:id="#+id/btn_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_weight="2.5"
android:text="CANCEL"
android:textColor="#155280"
android:textSize="14sp"
android:textStyle="bold"
android:visibility="visible" />
</LinearLayout>
<FrameLayout
android:id="#+id/test_bed"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<!-- We will add the DSLVFragment inside the FrameLayout in code -->
</LinearLayout>
and other require class can be download from github link that i given above.....
Actually if you see your code closly there's a method that you have mention
public void setListAdapter() {
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
}
So as you said :
"generally we create new adapter and pass it to listview like lv.setAdapter(adapter) , but here they just set ListAdapter, so we cant do lv.setAdapter(adapter)"
Can't you easily do this by easily generating an array based on your search and set it like the code ??
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(getActivity(), getItemLayout(),
R.id.text, list);
setListAdapter(adapter);
EDIT: I think you are asking the wrong question. Your main concern should be how to communicate between activity and fragments...since your search functionality is in activity and list is in fragment. So you need to setup an interface that basically passes on the search string to your fragment and there you can make an array and set it the same way you are doing right now.
Read this SO question and answer. In the answer you'll find one similar approach on passing data between activity and fragment.
Edit 2: Your main concern is to communicate from activity to fragment for this..declare an interface in your activity like this:
public interface FragmentCommunicator{
public void passDataToFragment(String someValue);
}
then call the interface at your text change listener..for example
FragmentCommunicator mfragmentCommunicator;
//your onCreate function
{
//your textchangelistenr
{
onTextChanged call
if(mfragmentCommunicator != null)
mfragmentCommunicator.passDataToFragment(Pass your string here)
}
then make your fragement implement this interface like
public class someFragment extends Fragment implements FragmentCommunicator
{
//this is your rest of the fragment
#Override
public void passDataToFragment(String somevalue)
{
//This function will get fired each time your text is changed since in your activity you are calling this same function in your textchange listener. the String somevalue will be the string that you passed from your activity
}
//rest of the code
.
.
.
//Don't forget to initialize your interface in fragment itself. Do this in your onAttach
like this
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
context = getActivity();
((MainActivity)context).fragmentCommunicator = this;
}
}
}
You can refer this link for any further clarifications. Check only the implementation of FragmentCommunicator
If you are using array as the base arraylist for adapter, just update this array and call adapater.notifyDataSetChanged(). This will update DSLV for sure as I have used same approach in one of my project.

Android AutoCompleteTextView with custom list item containing multiple views

I try to create a AutoCompleteTextView with custom list items, like showing a picture and a name in one list item. I know how to create it with 1 line of text in a list item but i'm a bit confused on who to do this with more views. I was thing about a ListAdapter and assigning the values to the right views. I'm pretty stuck here. I hope someone can give me a push in the right direction. Question is updated below.
Main activity:
public class AutocompleteCustomActivity extends Activity {
String[] firstView = {"Apple","Banana","Strawberry"};
String[] secondView = {"Green","Yellow","Red"};
AutoCompleteTextView autocomplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
// Simple 1 line list item
this.autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, firstView);
autocomplete.setAdapter(adapter);
*/
// 2 Lines of text in list item
this.autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.two_list_items, firstView);
autocomplete.setAdapter(adapter);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
UPDATE:
After a lot of hardcore Googling and trial and erroring i came up with this code. I think it's pretty oké but the list items keep showing after selecting one. I know it's the settext that opens the new listitems.
I found this post: Disable Android AutoCompleteTextView after user selects item from drop down
But i don't know what he means :( Anyone knows how to fix this?
package com.sb.autocompletecustom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.SimpleAdapter;
public class AutocompleteCustomActivity extends Activity {
AutoCompleteTextView autocomplete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Data to fill autocomplete
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> curGroupMap = new HashMap<String, String>();
list.add(curGroupMap);
curGroupMap.put("name", "Banana");
curGroupMap.put("color", "Yellow");
curGroupMap = new HashMap<String, String>();
list.add(curGroupMap);
curGroupMap.put("name", "Strawberry");
curGroupMap.put("color", "Red");
curGroupMap = new HashMap<String, String>();
list.add(curGroupMap);
curGroupMap.put("name", "Strawberry");
curGroupMap.put("color", "Black");
// 2 Lines of text in list item
this.autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.two_list_items, new String[] { "name", "color" }, new int[] { R.id.textView1, R.id.textView2 });
autocomplete.setAdapter(adapter);
autocomplete.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
Map<String, String> map = (Map<String, String>) p.getItemAtPosition(pos);
String itemName = map.get("name");
autocomplete.setText(itemName);
}
});
}
}
use a custom list adapter. you can inflate the layout and assign the values
public class AutoCompleteCursorAdapter extends CursorAdapter implements Filterable{
private TextView txtDrName, txtDrugName, txtDrugManufacturer;
private int rowResID;
private static Cursor c;
private String autoCompleteTextName;
Context context;
int layout;
public AutoCompleteCursorAdapter(Context context, int layout ) {
super(context, c);
// this.c = c;
this.context = context;
this.autoCompleteTextName = autoCompleteTextName;
this.layout = layout;
}
public long getItemId(int position) {
return position;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
txtDrName = (TextView)v.findViewById(R.id.txtAutoName) ;
....
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
txtDrName = (TextView) view.findViewById(R.id.txtAutoName) ;
}
#Override
public String convertToString(Cursor cursor) {
// this method dictates what is shown when the user clicks each entry in your autocomplete list
String name="";
name = cursor.getString(cursor.getColumnIndex("prefix"))+" "+cursor.getString(cursor.getColumnIndex("firstName"));
}
return name;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
// this is how you query for suggestions
if (getFilterQueryProvider() != null)
{ return getFilterQueryProvider().runQuery(constraint); }
if(constraint!=null){
DataBaseHelper db = new DataBaseHelper(context);
db.openDataBase();
if(autoCompleteTextName.equals(AppConstants.AUTOCOMPLETEDOCTORNAME)){
c = db.getStaffStartingWith((String) constraint);
}
else if (autoCompleteTextName.equals(AppConstants.AUTOCOMPLETEDRUGNAME)){
c = db.getDrugsForStartingWith((String) constraint);
}
c.moveToFirst();
db.close();
}
return c;
}
`

Categories

Resources