Android: Stuck on updating textView in custom adapter - java

I'm new to programming for Android (and Java) and have managed to get a custom adapter working, but am stuck on how to update textViews inside of it. Below you will see my score_save function with the code I want, but I'm not sure how to apply this to all rows of my adapter at once.
public class MainActivity extends Activity {
private ListView listView1;
private int currentPlayer;
private int currentScore;
ArrayList<Integer> allScoreChange = new ArrayList<Integer>();
ArrayList<Integer> allScore = new ArrayList<Integer>();
Button button_add, button_add_big, button_sub, button_sub_big,
button_add_num, button_save;
TextView name;
TextView score;
TextView scoreChange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Score score_data[] = new Score[] { new Score("NameA"),
new Score("NameB"), new Score("NameC"), new Score("NameD"),
new Score("NameE") };
//sets score lists to 0
for (int i = 0; i < 5; i++) {
allScoreChange.add(0);
allScore.add(0);
}
ScoreAdapter adapter = new ScoreAdapter(this,
R.layout.listview_item_row, score_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentScore = allScoreChange.get(position);
// Gets fields from current row
score = (TextView) view.findViewById(R.id.txtScore);
scoreChange = (TextView) view.findViewById(R.id.txtScoreChange);
currentPlayer = position;
}
});
button_save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
score_save();
}
});
}
public void score_save() {
// this needs to go through all rows of listview
currentPlayer = 0;
// update array with new score
allScore.set(currentPlayer, allScore.get(currentPlayer)
+ allScoreChange.get(currentPlayer));
// display new score
score.setText(allScore.get(currentPlayer));
// reset score change to zero
allScoreChange.set(currentPlayer, 0);
// display score change as blank
scoreChange.setText("");
}
}
Here's the XML for the row, I want to update txtScoreChange and txtScore with the values out of the allScoreChange and allScore ArrayLists. I cut out the code that defines these lists, in case you're wondering.
<?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="horizontal"
android:padding="10dp" >
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="70"
android:text="Name"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtScoreChange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:textColor="#ff0000"
android:textSize="22sp"
android:gravity="right" />
<TextView
android:id="#+id/txtScore"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="15"
android:text="1"
android:textColor="#666666"
android:textSize="22sp"
android:gravity="right" />
Here's my adapter:
public class ScoreAdapter extends ArrayAdapter<Score>{
Context context;
int layoutResourceId;
Score data[] = null;
public ScoreAdapter(Context context, int layoutResourceId, Score[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ScoreHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ScoreHolder();
holder.txtScore = (TextView)row.findViewById(R.id.txtScore);
holder.txtScoreChange = (TextView)row.findViewById(R.id.txtScoreChange);
holder.txtName = (TextView)row.findViewById(R.id.txtName);
row.setTag(holder);
}
else
{
holder = (ScoreHolder)row.getTag();
}
Score scoreData = data[position];
holder.txtName.setText(scoreData.name);
holder.txtScore.setText(scoreData.score);
return row;
}
static class ScoreHolder
{
TextView txtScore;
TextView txtName;
TextView txtScoreChange;
}
}

Call adapter.notifyDataSetChanged(). That will cause it to repopulate the listview, calling adapter.getView on all visible views. Have getView() set the correct values for its row.

Related

adding space to make each list item bigger

My app that I am creating has two listviews. My second listview does not look the same as my second one. The lines that seperate each item are too close to the text, but I want them to have space on both the top and bottom, like the first list. I have tried to change the padding and the margins but that does not works and I have also tried to change it in one of the Java classes but I get error messages.
Here are two pictures for comparison(The first list is on the left and the second list is on the right)
The second list:
<ListView
android:id="#+id/countryselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_above="#+id/checkItem"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="60dp"
android:clickable="false"/>
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO ITEM AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
<Button
android:id="#+id/checklist"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2"
My first list:
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="left"
android:text="Favorites"
android:textColor="#222"
android:textSize="15dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="2dp"
android:textStyle="normal" />
<Button
android:id="#+id/tofavorites"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2" />
<ListView
android:layout_marginTop="60dp"
android:id="#+id/countrieselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="false" />
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Here Is my adapter class for the second list:
public class AdapterFavorite extends BaseAdapter {
ArrayList<String> items;
ArrayList<String> items1;
LayoutInflater inflater;
ArrayList selectedItems;
List<Item> dummyItems;
ArrayList<Integer> itemsValue = new ArrayList<>();
Activity activity;
DbUtility dbUtility;
Context context;
AdapterFavorite(Activity activity, ArrayList<String> items, Context context) {
this.items = items;
inflater = activity.getLayoutInflater();
selectedItems = new ArrayList<String>();
this.activity = activity;
this.context = context;
dbUtility = new DbUtility(activity);
}
#Override
public int getCount() {
return items.size();
}
#Override
public String getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
dbUtility.open();
View v = view;
if (v == null) {
v = inflater.inflate(R.layout.checkboxlayoutfavorite, null);
}
TextView textview_countries = (TextView) v.findViewById(R.id.Textview_languages);
Button button = (Button) v.findViewById(R.id.checkbox);
items1 = new ArrayList<>();
textview_countries.setText(items.get(i));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
////Where I tried to add/move items when the checkbox is clicked
dbUtility.delete_byID(items.get(i));
items.remove(i);
notifyDataSetChanged();
}
});
return v;
}
}
Here is my main Java class for the second listL:
ublic class FavoriteActivity extends AppCompatActivity {
DbUtility dbUtility;
List<Item> dummyItems = new ArrayList<>();
Button mainList;
KeyboardPrefManager keyboardPrefManager;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView chl = (ListView) findViewById(R.id.languageselector);
mainList = (Button) findViewById(R.id.checklist);
chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
items = new ArrayList<>();
dbUtility = new DbUtility(this);
dbUtility.open();
dummyItems = dbUtility.getAllContacts();
keyboardPrefManager = new KeyboardPrefManager(this);
for (int a = 0; a < dummyItems.size(); a++) {
items.add(dummyItems.get(a).getValue());
}
mainList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FavoriteActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
AdapterFavorite adapter = new AdapterFavorite(this, items, this);
chl.setAdapter(adapter);
chl.setEmptyView(findViewById(R.id.emptyElement));
chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String item = items.get(i); // Getting the dummy item from the List with position i
Toast.makeText(FavoriteActivity.this, "Clicked on " + item, Toast.LENGTH_SHORT).show();
keyboardPrefManager.selectKeyboard(item);
}
});}}
Please check your list item xml for both list same or not.Thanks

Read all values inside a list view Android

I am using a loop to read all the spinner elements (inside a cardview) in the listview.
But the loop gives one item less i.e. the last item.
I have included all the source code.
What may be the problem?
Is there any other way to read all the items in listview?
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/ll_gpa"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ListView
android:id="#+id/listSubs"
android:scrollbars="none"
android:layout_height="0dip"
android:layout_width="match_parent"
android:layout_weight="1"
/>
<Button
android:text="Calculate GPA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnGpa"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Single Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv_subject"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/rl_subject"
>
<TextView
android:id="#+id/subTitle"
android:textSize="16sp"
android:text="Subject"
android:layout_toStartOf="#+id/subGrade"
android:layout_toLeftOf="#+id/subGrade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:dropDownWidth="40dp"
android:textAlignment="center"
android:entries="#array/grades"
android:id="#+id/subGrade"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity
public class MainActivity extends AppCompatActivity {
private static SubjectArrayAdapter adapter;
private ProgressDialog progress;
JsonArray subs = new JsonArray();
JsonArray dataGrades = new JsonArray();
ListView listView;
ArrayList<SubjectClass> subjects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = new GetSubNames().execute();
subs = res.getAsJsonArray("subjects");
for (int i = 0; i < subs.size(); i++){
JsonObject temp = subs.get(i).getAsJsonObject();
subjects.add(new SubjectClass(temp.get("subCode").getAsString(), temp.get("subTitle").getAsString()));
}
adapter = new SubjectArrayAdapter(subjects,GpaActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Button btnGpa = (Button) findViewById(R.id.btnGpa);
btnGpa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CalcGPA().execute();
JsonArray temparr = new JsonArray();
for (int i = 0; i < listView.getChildCount(); i++) {
// Get row's spinner
View listItem = listView.getChildAt(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
dataGrades = temparr;
}
});
}
}
Custom Class
class SubjectClass{
String title;
String code;
SubjectClass(String code, String title) {
this.code = code;
this.title = title;
}
String getTitle(){
return this.title;
}
String getCode(){
return this.code;
}
void setCode(String code){
this.code = code;
}
void setTitle(String title){
this.title = title;
}
}
Custom ArrayAdapter
public class SubjectArrayAdapter extends ArrayAdapter<SubjectClass>{
private ArrayList<SubjectClass> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public SubjectArrayAdapter(ArrayList<SubjectClass> data, Context context) {
super(context, R.layout.item_subject, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
SubjectClass dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_subject, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.subTitle);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
viewHolder.txtName.setText(dataModel.getCode() + " " + dataModel.getTitle());
// Return the completed view to render on screen
return convertView;
}
}
for (int i = 0; i < listView.getCount(); i++) {
// Get row's spinner
View listItem = listView.getItemAtPosition(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
Check for above code in main activity. Use .getCount() instead .getChildCount()
and use .getItemAtIndex() instead .getChildAt().
I hope this solves the issue.

List views and custom adapters: resource id for textview

I'm trying to implement my own ListView design with a custom adapter. But whenever I run my program, I get this error "ArrayAdapter: You must supply a resource ID for a TextView".
Here is my Custom Adapter
public class LayoutAdapter extends ArrayAdapter {
List list = new ArrayList();
public LayoutAdapter (Context context, int resource) {
super(context,resource);
}
static class DataHandler {
TextView accountName;
TextView availableBalance;
TextView totalBalance;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_layout,parent,false);
handler = new DataHandler();
handler.accountName = (TextView) row.findViewById(R.id.account_name);
handler.availableBalance = (TextView) row.findViewById(R.id.available_balance);
handler.totalBalance = (TextView) row.findViewById(R.id.total_balance);
row.setTag(handler);
}
else {
handler = (DataHandler)row.getTag();
}
Account account;
account = (Account)this.getItem(position);
handler.accountName.setText(account.returnName());
handler.availableBalance.setText("Available Balance: $"+account.returnAvailableBalance());
handler.totalBalance.setText("Total Balance: $"+account.returnTotalBalance());
return row;
}
}
Here is my custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="8dp">
<TextView
android:text="#string/str_account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account_name"
android:height="80dp"
android:textSize="24sp"
android:gravity="center_vertical" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/account_name">
<TextView
android:text="#string/str_available_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/available_balance"
android:textSize="16sp"
android:layout_gravity="right"
android:paddingTop="30dp" />
<TextView
android:text="#string/str_total_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/total_balance"
android:textSize="16sp"
android:layout_gravity="right" />
</LinearLayout>
</RelativeLayout >
Here is my main activity
LayoutAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new LayoutAdapter(getApplicationContext(),R.layout.custom_layout);
ArrayList<Account> accounts = new ArrayList<>();
accounts.add(new Account ("Checking",5.00));
accounts.add(new Account ("Cash",50.00));
Account acc1 = new Account("Checking",5.00);
Account acc2 = new Account("Cash",50.00);
adapter.add(acc1);
adapter.add(acc2);
listView.setAdapter(adapter);

ListView not Appearing

I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res``/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().

customised listview using arrayadapter class in android

how to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.

Categories