I have a listview with several buttons in which the button.text property populated with several child names from a an sqlite database.
I need to retrieve tasks specificaly assigned to each child when the child's button is clicked (possibly using the text property of the button(which is populated with the child name) ).
I have 3 java files that i am working (ChildDatabase, ChildListAdapter, ChildList) with and 2 xml files(fragment_child_list_layout, fragment_child_list).
Where can I set an onClick event for the buttons in my list view. And how can i differentiate from each button if only ONE BUTTON is delcared?
This is my ChildDatabase file
package com.example.victor.kidsrewards;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildDataBase {
private SQLiteDatabase db;
private ChildSQLiteHelper childSQLiteHelper;
String _parentName = Globals._username;
public ChildDataBase(Context context) {
childSQLiteHelper = new ChildSQLiteHelper(context);
db = childSQLiteHelper.getWritableDatabase();
}
public void Close() {
db.close();
}
public void createChild(String childNameText, String nickNameText, String genderText, int ageText) {
String query = "select * from child";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
ContentValues contentValues = new ContentValues();
contentValues.put("id", count);
contentValues.put("childname", childNameText);
contentValues.put("nickname", nickNameText);
contentValues.put("age", ageText);
contentValues.put("gender", genderText);
contentValues.put("parent", _parentName);
//insert
db.insert("child", null, contentValues);
}
public List<ChildUser> getChildren() {
List<ChildUser> childList = new ArrayList<ChildUser>();
//select columns
String[] tableColumns = new String[]{"id", "childname", "nickname"};
Cursor cursor = db.query("child", tableColumns, "parent =? ", new String[]{_parentName}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChildUser child = new ChildUser();
//take values from database
child.setId(cursor.getInt(0));
child.setChildName(cursor.getString(1));
child.setNickName(cursor.getString(2));
//add to db
childList.add(child);
cursor.moveToNext();
}
return childList;
}
public String[] getChildNames() {
String[] tableColumns = new String[]{"childname"};
Cursor cursor = db.query("child", tableColumns, "parent =?", new String[]{_parentName}, null, null, null);
String[] array = new String[cursor.getCount()];//sets the length of the array
int i = 0;
while (cursor.moveToNext()) {
String uname = cursor.getString(cursor.getColumnIndex("childname"));
array[i] = uname;
i++;
}
return array;
}
}
This is my ChildListAdapter
Displays same button over again with different text property
package com.example.victor.kidsrewards;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildListAdapter extends ArrayAdapter<ChildUser> {
private final Context context;
private final List<ChildUser> childList;
public ChildListAdapter(Context context, List<ChildUser> childList){
super(context, R.layout.fragment_child_list_layout, childList);//fragment_child_list
this.context = context;
this.childList= childList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
return rowView;
}
ChildList class
package com.example.victor.kidsrewards;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChildList extends ListFragment {
private ChildDataBase cdb;
public ChildList() {
// Required empty public constructor
}
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_child_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cdb = new ChildDataBase(getContext());
setListAdapter(new ChildListAdapter(getContext(), cdb.getChildren()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
}
fragment_child_list_layout.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/childButton"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
fragment_child_list.xml
<FrameLayout 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"
tools:context="com.example.victor.kidsrewards.ChildList">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="TODO TEXT GOES_HERE">
</ListView>
</FrameLayout>
You can set the OnClickListener for the Button inside the getView() method of the adapter. The position argument can be used to identify which button was clicked.
See the code,
#Override
public View getView(final int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String selectedChild = childList.get(position).getNickName();
// do something with selected item
}
});
return rowView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOncLickListener(new OnclickListener() {
public void onClick() {
// do something for click each row
}
return rowView;
}
Related
I have got a ListView with a custom UserAdapter, which holds a SparseBooleanArray with the currently activated (selected) Ids.
The method toggleSelection(position) creates or deletes an entry from my SparseBooleanArray.
So I have the possibility to call this method in my DriverFragment within the listView.onItemClickListener() and as a result the background drawable of the item changes on click.
Now i want to preselect one item in the DriverSelectionFragment programmatically.
So far i can add it to my SparseBooleanArray but the background doesn't change when entering the Fragment.
What am I missing? Do i have to notify the listView? I'm adding the selected item in onViewCreated(), so it should work.
EDIT: Added the xml files
The UserAdapter:
package com.example.convictedDriver.Adapters;
import android.content.Context;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.convictedDriver.Database.User;
import com.example.convictedDriver.R;
import com.mikhaellopez.circularimageview.CircularImageView;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class UserAdapter extends ArrayAdapter<User> {
// Declare Variables
private List<User> userList;
private ViewGroup parent;
private LayoutInflater inflater;
private SparseBooleanArray mSelectedItemsIds;
public UserAdapter(Context context, int resource, List<User> userList) {
super(context, resource, userList);
mSelectedItemsIds = new SparseBooleanArray();
this.userList = userList;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView name;
TextView ratio;
CircularImageView circularImageView;
}
#Override
public View getView(int position, View view, #NotNull ViewGroup parent) {
final ViewHolder holder;
this.parent = parent;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_item, null, false);
// Locate the TextViews and Imageview in list_item.xml
holder.name = view.findViewById(R.id.user_name_text);
holder.ratio = view.findViewById(R.id.user_ratio_text);
holder.circularImageView = view.findViewById(R.id.list_item_imageView);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews and ImageView
holder.name.setText(userList.get(position).getUsername());
holder.ratio.setText(String.valueOf((userList.get(position).getRatio())));
holder.circularImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return view;
}
#Override
public void remove(User user){
userList.remove(user);
notifyDataSetChanged();
}
public List<User> getUserList(){
return userList;
}
// Toggles the selection state of a given item position
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
Log.i("Debug", "Position "+position+" changed state from "+!mSelectedItemsIds.get(position)+" to "+
mSelectedItemsIds.get(position));
}
// Removes all selections
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
// Helper Class for toggling a specific item position
private void selectView(int position, boolean value) {
if (value) {
mSelectedItemsIds.put(position, value);
}
else {
mSelectedItemsIds.delete(position);
}
}
// Returns the amount of selected items
public int getCheckedCount() {
int num = 0;
for (int i = 0; i < mSelectedItemsIds.size(); i++) {
if (mSelectedItemsIds.valueAt(i)) {
num++;
}
}
return num;
}
// Returns the SparseBooleanArray for the ListView
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
}
The DriverFragment:
package com.example.convictedDriver.Fragments.Drive;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.Navigation;
import com.example.convictedDriver.Adapters.UserAdapter;
import com.example.convictedDriver.Classes.MyListSorter;
import com.example.convictedDriver.Classes.MyToast;
import com.example.convictedDriver.Database.IntegratedDatabase.UserDbHelper;
import com.example.convictedDriver.Database.User;
import com.example.convictedDriver.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class DriveFragment extends Fragment {
private FloatingActionButton fabContinue;
private ArrayList<User> userList;
private ListView listView;
private UserAdapter adapter;
private SparseBooleanArray checked;
public DriveFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_drive, container, false);
// Getting all the users out of the database and sort them
UserDbHelper db = UserDbHelper.getInstance(getContext());
userList = db.getAllUsers();
MyListSorter.sort(userList, MyListSorter.SortType.RATIO);
// Locate the ListView and in fragment_drive.xml
listView = view.findViewById(R.id.drive_listView);
fabContinue = view.findViewById(R.id.fab_continue);
return view;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Pass userList to UserAdapter Class
adapter = new UserAdapter(getContext(), R.layout.list_item, userList);
// Binds the Adapter to the ListView
listView.setItemsCanFocus(false);
listView.setAdapter(adapter);
checked = adapter.getSelectedIds();
Toast.makeText(getContext(), "OnViewCreated: "+checked.toString(),Toast.LENGTH_SHORT).show();
// Capture ListView item click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toggle the ListViewItems State
adapter.toggleSelection(position);
Toast.makeText(getContext(), "OnItemClick: "+checked.toString(),Toast.LENGTH_SHORT).show();
}
});
/*
* Create an array out of the selectedUsers Arraylist and pass it
* towards DriveSelectionFragment
*/
fabContinue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
checked = adapter.getSelectedIds();
Toast.makeText(getContext(), "OnClickListener: "+checked.toString(),Toast.LENGTH_SHORT).show();
if(adapter.getCheckedCount() > 2) {
User[] userArray = new User[checked.size()];
int j = 0;
for (int i = (checked.size() - 1); i >= 0; i--){
if (checked.valueAt(i)){
userArray[j] = adapter.getItem(checked.keyAt(i));
j++;
}
}
//listView.clearChoices();
adapter.removeSelection();
DriveFragmentDirections.ActionDriveFragmentToDriveSelectionFragment action =
DriveFragmentDirections.actionDriveFragmentToDriveSelectionFragment(userArray);
Navigation.findNavController(v).navigate(action);
}else{
new MyToast(getContext(), "Select at least 3 Users!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
The DriverSelectionFragment:
package com.example.convictedDriver.Fragments.Drive;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.convictedDriver.Adapters.UserAdapter;
import com.example.convictedDriver.Database.User;
import com.example.convictedDriver.R;
import java.io.File;
import java.util.ArrayList;
public class DriveSelectionFragment extends Fragment {
private ArrayList<User> selectedDrivers = new ArrayList<>();
private ArrayList<User> userList = new ArrayList<>();
private ListView listView;
private UserAdapter adapter;
private User driver;
private View view;
private SparseBooleanArray checked;
public DriveSelectionFragment(){
// Empty constructor is needed
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_drive_selection, container, false);
listView = view.findViewById(R.id.driveSelection_listView);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Receive an ArrayList as argument, including all the userList
if(getArguments() != null){
DriveSelectionFragmentArgs args = DriveSelectionFragmentArgs.fromBundle(getArguments());
userList = arrayToList(args.getSelectedUsers());
}
// Calculate the user with the highest ratio out of the userList
// and add it to the selectedDrivers ArrayList
driver = calculateDriver(userList);
selectedDrivers.add(driver);
Toast.makeText(getContext(), "Driver: "+driver.getUsername(),Toast.LENGTH_SHORT).show();
// Initialize listView and set the adapter
adapter = new UserAdapter(getContext(),R.layout.list_item, userList);
listView.setItemsCanFocus(false);
int driverPos = getDriverPosition(userList, driver);
Toast.makeText(getContext(), "DriverPosition: "+driverPos,Toast.LENGTH_SHORT).show();
adapter.toggleSelection(getDriverPosition(userList,driver));
checked = adapter.getSelectedIds();
Toast.makeText(getContext(), "OnViewCreated: "+checked.toString(),Toast.LENGTH_SHORT).show();
// Binds the Adapter to the ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toggle the ListViewItems State
adapter.toggleSelection(position);
Toast.makeText(getContext(), "OnItemClick: "+checked.toString(),Toast.LENGTH_SHORT).show();
}
});
}
/*
*
* Calculates a user out of a given list with the highest ratio
*
*/
private User calculateDriver(ArrayList<User> list){
User currUser = list.get(0);
for (User user : list){
if(user.getRatio() >= currUser.getRatio()){
Log.i("Test", user.getRatio() +">"+ currUser.getRatio());
currUser = user;
Log.i("Test", "Changed driver to "+currUser);
}
}
return currUser;
}
private int getDriverPosition(ArrayList<User> list, User driver){
int position = 0;
for (User user: list) {
if (user.getId() == driver.getId()){
return position;
}else{
position++;
}
}
return -1;
}
The fragment_drive_selection.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Fragments.Drive.DriveSelectionFragment">
<ListView
android:id="#+id/driveSelection_listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:divider="#null"
android:dividerHeight="3dp"
android:layout_marginVertical="5dp"
android:choiceMode="multipleChoice"
android:listSelector="#android:color/transparent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The list_item.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?attr/selectableItemBackground"
android:background="#drawable/list_item_selector">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/list_item_imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
app:civ_border="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:src="#drawable/avatar_1"/>
<TextView
android:id="#+id/user_name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginStart="8dp"
android:autoSizeTextType="uniform"
android:text=""
android:textColor="#color/colorSpotifyWhite"
android:textSize="22sp"
app:layout_constraintBottom_toTopOf="#+id/user_ratio_text"
app:layout_constraintStart_toEndOf="#+id/list_item_imageView"
app:layout_constraintTop_toTopOf="parent"
tools:text="name" />
<TextView
android:id="#+id/user_ratio_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:text=""
tools:text="ratio"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#id/list_item_imageView"
app:layout_constraintTop_toBottomOf="#id/user_name_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
The list_item_selector.xml File:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- pressed -->
<item android:state_enabled="true"
android:state_pressed="true" android:drawable="#drawable/list_item_background_selected" />
<!-- focused -->
<item android:state_enabled="true"
android:state_focused="true" android:drawable="#drawable/list_item_background_selected" />
<!-- selected -->
<item android:state_enabled="true"
android:state_selected="true" android:drawable="#drawable/list_item_background_selected" />
<!-- default -->
<item android:state_enabled="true"
android:state_checked="true" android:drawable="#drawable/list_item_background_selected" />
<item android:state_activated="true"
android:drawable="#drawable/list_item_background_selected" />
<!-- default -->
<item android:drawable="#drawable/list_item_background" />
</selector>
You have to use setItemChecked on ListView to select the item when set Multiple Choice Mode. Check below:
int selctedPosition = getDriverPosition(userList,driver);
adapter.toggleSelection(selctedPosition);
// Binds the Adapter to the ListView
listView.setAdapter(adapter);
listView.setItemChecked(selctedPosition, true);
My app is to perform ListView. When it was running, the error message notified that "Unfortunately, App has stopped". Here is my code.
package com.example.admin.customadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Nation>nationifo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.ListViewNation);
nationifo = new ArrayList<>();
nationifo.add(new Nation("VietNam",1945));
nationifo.add(new Nation("Malaysia",1975));
nationifo.add(new Nation("Laos",1943));
NationAdapter adp = new NationAdapter(
MainActivity.this,
R.layout.nation_list,
nationifo
);
listView.setAdapter(adp);
}
}
Nation.java
package com.example.admin.customadapter;
public class Nation {
public String name;
public Integer year;
public Nation(String Name, Integer Year){
Name = name;
Year = year;
}
}
NationAdapter.java
package com.example.admin.customadapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NationAdapter extends BaseAdapter {
Context mycontext;
int mylayout;
List<Nation>arrayNation;
public NationAdapter (Context context, int layout, List<Nation>nationList){
mycontext = context;
mylayout = layout;
arrayNation = nationList;
}
public int getCount() {
return arrayNation.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(mylayout,null);
TextView txtv1 = (TextView) convertView.findViewById(R.id.textView);
txtv1.setText(arrayNation.get(position).name);
TextView txtv2 =(TextView) convertView.findViewById(R.id.textView2);
txtv2.setText(String.valueOf(arrayNation.get(position).year));
return convertView;
}
}
nation_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background = "#ffffff">
<TextView
android:textColor="#ff0400"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/textView" />
<TextView
android:textColor="#0022ff"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
</LinearLayout>
My Android Studio is 2.2. But I don't think that this version is diferrent to another.
try to use the following
convertView = inflater.inflate(mylayout,parent,false);
instead of
convertView = inflater.inflate(mylayout,null);
I am having problem with changing color of Textview in custom Listview.
My xml file is column.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:id="#+id/cid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textSize="30dp"
android:visibility="gone"/>
<TextView
android:id="#+id/cname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25dp"
android:textColor="#f60505" />
<TextView
android:id="#+id/amt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#2ec31d"
android:textAlignment="center" />
</LinearLayout>
and ListViewAdapter.java goes like this
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by XYZ on 06-05-2016.
*/
public class ListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String,String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String,String>>list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.colunm_row,null);
holder = new ViewHolder();
holder.textFirst=(TextView)convertView.findViewById(R.id.cid);
holder.textSecond=(TextView)convertView.findViewById(R.id.cname);
holder.textThird=(TextView)convertView.findViewById(R.id.amt);
txtFirst = (TextView) convertView.findViewById(R.id.cid);
txtSecond = (TextView)convertView.findViewById(R.id.cname);
txtThird = (TextView) convertView.findViewById(R.id.amt);
convertView.setTag(holder);
}else {
holder =(ViewHolder)convertView.getTag();
holder.textFirst.setText("");
holder.textSecond.setText("");
holder.textThird.setText("");
}
HashMap<String,String> map= list.get(position);
/* txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));*/
holder.textFirst.setText(map.get(FIRST_COLUMN));
holder.textSecond.setText(map.get(SECOND_COLUMN));
holder.textThird.setText(map.get(THIRD_COLUMN));
return convertView;
}
static class ViewHolder{
TextView textFirst;
TextView textSecond;
TextView textThird;
}
}
DisplayActivity :
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AccDisplay extends AppCompatActivity {
private ArrayList<HashMap<String,String>> arrayList;
Cursor c;
SQLiteDatabase db;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc_display);
ListView listView = (ListView)findViewById(R.id.AcclistView);
arrayList = new ArrayList<HashMap<String, String>>();
db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);
c=db.rawQuery("select c.c_id ,c.c_name, ((select CASE WHEN (sum(cr.amount)) IS Null THEN 0 ELSE sum(cr.amount) END from credit_master cr where c.c_id=cr.c_id) ) - ((select CASE WHEN (sum(d.amount)) IS NULL THEN 0 ELSE sum(d.amount) END from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c ORDER BY c.c_name ASC",null);
//c=db.rawQuery("select c.c_id ,c.c_name, ((select sum(cr.amount) from credit_master cr where c.c_id=cr.c_id) ) - ((select sum(d.amount) from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c",null);
try {
if (c!=null){
if(c.moveToFirst()){
Map<String,String> tem = new HashMap<String ,String>();
tem.clear();
arrayList.clear();
listView.setAdapter(null);
int cnt = c.getCount();
Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
do {
tem = new HashMap<String,String>();
tem.clear();
tem.put(FIRST_COLUMN, c.getString(0));
tem.put(SECOND_COLUMN,c.getString(1));
tem.put(THIRD_COLUMN,c.getString(2));
arrayList.add((HashMap<String, String>) tem);
}while (c.moveToNext());
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) (view.findViewById(R.id.cid));
int str = Integer.parseInt(tv.getText().toString());
Toast.makeText(AccDisplay.this,"Clicked"+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(AccDisplay.this,Details.class);
intent.putExtra("name",str);
startActivity(intent);
}
});
}
protected void onRestart(){
super.onRestart();
Intent inte = getIntent();
finish();
startActivity(inte);
}
}
I am using same layout file for three different activities.
I want to display different color of each TextView in Different Activity.
I have tried this but didn't work
LayoutInflator inflator = (LayoutInflator)getSystemService(Context.LAYOUT_INFLATOR_SERVICE);
View vi = inflator.inflate(R.layout.column,null);
TextView tv = (TextView) vi.findViewById(R.id.amt);
tv.setTextColor(Color.BLACK);
I can change color of TextView in OnItemClickListener but i want to display color while displaying data.
I am having Debit/Credit activity which uses same Adapter class and column.xml layout for displaying data in listview.
I want to display TextView1 in black color font and TextView2 in Green color with big font size in Activity 1. and different color in different activity.
You can pass different flags in adapter constructor to adapter for identifying activity if same adapter you are using for other activities, and can put conditions according to the flag set colors to the TextView in adapter programmatically. textView.setTextColor(put_your_color);
I meet a problem developing an android project.
Using adapter, I place many items in a ListView, and there is an ImageButton in each item. Now I want to set a click listener for these ImageButtons. What should I do?
This achieves your desired result. Its functionality is the button itself has a click response different from the container, which also has a response.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Toast.makeText( MainActivity.this,
"List item clicked",
Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
items.add( "item3");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.List;
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
Toast.makeText( context,
"ImageButton clicked",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
item.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:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="28sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:src="#drawable/emo_im_cool" />
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list" />
Try it out and hopefully you can see what's going on to learn what you need
I am working with custom listView in android. but I cant able click the item in listview.
my code is
Adapter code(BankArrayListAdapter.java)
package com.example.customlist;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class BankArrayListAdapter extends ArrayAdapter<Bank>{
private int resource;
private LayoutInflater inflater;
private Context ctx;
public BankArrayListAdapter(Context context, int resourceId, List<com.example.customlist.Bank> ls)
{
super(context, resourceId, ls);
resource = resourceId;
inflater = LayoutInflater.from( context );
ctx=context;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
/* create a new view of my layout and inflate it in the row */
convertView = inflater.inflate( resource, null );
/* Extract the city's object to show */
Bank bank = (Bank) getItem(position);
/* Take the TextView from layout and set the city's name */
TextView txtName = (TextView) convertView.findViewById(R.id.textView1);
txtName.setText(bank.getName());
/* Take the TextView from layout and set the city's wiki link */
TextView txtWiki = (TextView) convertView.findViewById(R.id.textView2);
txtWiki.setTextSize(13);
txtWiki.setMovementMethod(LinkMovementMethod.getInstance());
txtWiki.setText(bank.getUrl());
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) convertView.findViewById(R.id.imageView1);
String uri = "drawable/" + bank.getLogo();
int imageResource = ctx.getResources().getIdentifier(uri, null, ctx.getPackageName());
Drawable image = ctx.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
package com.example.customlist;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
ListView lv;
List<Bank> ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
ls= new ArrayList<Bank>();
ls.add(new Bank("sbi","State Bank Of India","http://www.sbi.com"));
ls.add(new Bank("iob", "India Overseas Bank","http://www.iob.com"));
ls.add(new Bank("icici","ICICI","http://www.icici.com"));
//lv.setAdapter( new BankArraylistA);
lv.setAdapter( new BankArrayListAdapter(Main.this, R.layout.banklist, ls ) );
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(Main.this,"Your Listener Works!",Toast.LENGTH_SHORT).show();
// System.out.println("Name: "+ls.get(position).getName());
// String s =(String) ((TextView) v.findViewById(R.id.From)).getText();
// Toast.makeText(Messages.this, s, Toast.LENGTH_LONG).show();
}
});
System.out.println(ls);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml file goes like this
<LinearLayout 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:descendantFocusability="blocksDescendants"
tools:context=".Main" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Thanks in advance
Regards,
Sathish
I had the same problem and I solved by add this code to getView() method in my custom adapter class, yours BankArrayListAdapter.java
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.v("LV_ITEM", "Position of item is " + position);
}
});