i have listView, and there are checkbox, imageView, TextView. I wanna pass that images, that was checked in listView. I know that's doing with bundle, but how to do the checkbox part? I have checkbox, but i don't know how to initialize it.
Here's the adapter part.
public class MyAdapter extends ArrayAdapter<MyAdapter> {
String names[];
int flags[];
Context mContext;
public MyAdapter(Context context, String[] languageNames, int[] countryFlags) {
super(context, R.layout.listview_items);
this.names = languageNames;
this.flags = countryFlags;
this.mContext = context;
}
#Override
public int getCount() {
return names.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_items, parent, false);
mViewHolder.mFlag = convertView.findViewById(R.id.imageView);
mViewHolder.mLanguage = convertView.findViewById(R.id.textView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mFlag.setImageResource(flags[position]);
mViewHolder.mLanguage.setText(names[position]);
return convertView;
}
static class ViewHolder {
ImageView mFlag;
TextView mLanguage;
}}
You see there's only an image and textview. How to add checkbox to there?
Here's the listView part.
public class FragmentLanguage extends Fragment {
View mainView;
ListView listView;
Context mContext;
Button next;
MyAdapter adapter;
ArrayList<Integer> mItems = new ArrayList<>();
int[] images = {R.drawable.download,
R.drawable.download,
R.drawable.download,
R.drawable.download,
R.drawable.download,
R.drawable.download,
R.drawable.download,
R.drawable.download};
String[] languages = {"Armenian", "Russian", "US English", "Portugal",
"Spanish", "Georgian", "French", "Italian"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.listview, container, false);
listView = mainView.findViewById(R.id.list_view);
listView.setAdapter(adapter);
adapter = new MyAdapter(getActivity(), languages, images);
listView.setAdapter(adapter);
next = mainView.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return mainView;
}}
1)How to add the checkbox part? 2) How to send images from this fragment to another fragment with bundle? Thanks. I'll write the bundle part here
next.setOnClickListener(new View.OnClickListener()
OPTION 1:
make a list of Int val listOfSelectedImages = arrayListOf()
checkBox.setOnClickListener {
if (checkBox.isChecked) {
//when checked add image(example R.id.image1) to list
} else {
//remove from the list
}
}
from one fragment to another:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
val mFragment2 = Fragment2()
val bundle = Bundle()
bundle.putParcelableArrayList(KEY, listOfSelectedImages)
mFragment2.arguments = bundle
supportFragmentManager.beginTransaction().add(R.id.fragment_container, mFragment2)
.commit()
}
});
in fragment 2 go val list = getArguments.getParcelableArrayList(KEY)
Related
I need to change the clicked text in listview using a ProgramAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
String[] programName = {"ex1", "ex2", "ex3"}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProgram = findViewById(R.id.listView);
ProgramAdapter programAdapter = new ProgramAdapter(this, programName);
lvProgram.setAdapter(programAdapter);
}}
ProgramAdapter.java:
public class ProgramAdapter extends ArrayAdapter<String> {
Context context;
String[] programName;
public ProgramAdapter(Context context, String[] programName) {
super(context, R.layout.single_item2, R.id.titulo, programName);
this.context = context;
this.programName = programName;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View singleItem = convertView;
ProgramViewHolder holder = null;
if(singleItem == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false);
holder = new ProgramViewHolder(singleItem);
singleItem.setTag(holder);
}
else{
holder = (ProgramViewHolder) singleItem.getTag();
}
holder.programTitle.setText(programName[position]);
}
}
My attempt was that:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
This changes the text for a moment, but every time you go down the list and up again, the text goes back to the default text.
Disclaimer! The code is working fine but it isn't efficient.
The problem is that I have to click the FAB TWICE before the row is added to the
list view. I want to be able to click the FAB just once so the row is added to
the list view!
ListItems.java
public class ListItems {
int icon;
String name;
String detail;
public ListItems(int icon,String name,String detail){
super();
this.icon = icon;
this.name = name;
this.detail = detail;
}
public String getTitle() {
return name;
}
public String getDescription() {
return detail;
}
public int getIcon() {
return icon;
}
}
............Adapter........
ListItemHelper.java
public class ListItemHelper extends ArrayAdapter<ListItems> {
private final Context context;
private final ArrayList<ListItems> itemsArrayList;
public ListItemHelper(Context context, ArrayList<ListItems> itemsArrayList) {
super(context, R.layout.list_item, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
}
#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.list_item, parent, false);
ImageView iconView = (ImageView) rowView.findViewById(R.id.iv_list_icon);
TextView labelView = (TextView) rowView.findViewById(R.id.tv_list_name);
TextView valueView = (TextView) rowView.findViewById(R.id.tv_detail_list);
labelView.setText(itemsArrayList.get(position).getTitle());
valueView.setText(itemsArrayList.get(position).getDescription());
iconView.setImageResource(itemsArrayList.get(position).getIcon());
return rowView;
}
}
And the fragment activity...
FragmentActivity.java
...
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//This is where the problem is ..I think!
fabCall = (FloatingActionButton) view.findViewById(R.id.fab_menu_call);
fabCall.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
list = (ListView) getActivity().findViewById(R.id.list);
list.setAdapter(adapter);
adapter = new ListItemHelper(getActivity(),generateData());
}
});
}
// Or may the problem is here.. I don't know!
private ArrayList<ListItems> generateData() {
ArrayList<ListItems> items = new ArrayList<ListItems>();
items.add(new ListItems(R.drawable.ic_shortcut_call,"Call","Shortcut added"));
return items;
}
...
here is the problem you are doing everything thing ok the but click in fab is first setting the adapter call and then puts the new data into an adapter try this code
fabCall.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
list = (ListView) getActivity().findViewById(R.id.list);
//first fill the adapter with updated list
adapter = new ListItemHelper(getActivity(),generateData())
// then set the adapter
list.setAdapter(adapter);
//notify change
adapter.notifyDataSetChanged();
;
}
});
Try the following:
Adapter:
public class ListItemHelper extends ArrayAdapter {
private Context context;
public ListItemHelper(Context context, ArrayList<ListItems> itemsArrayList) {
super(context, R.layout.list_item, itemsArrayList);
this.context = context;
}
#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.list_item, parent, false);
ImageView iconView = (ImageView) rowView.findViewById(R.id.iv_list_icon);
TextView labelView = (TextView) rowView.findViewById(R.id.tv_list_name);
TextView valueView = (TextView) rowView.findViewById(R.id.tv_detail_list);
labelView.setText(((ListItems)getItem(position)).getTitle());
valueView.setText(((ListItems)getItem(position)).getDescription());
iconView.setImageResource(((ListItems)getItem(position)).getIcon());
return rowView;
}
}
Activity:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fabCall = (FloatingActionButton) view.findViewById(R.id.fab_menu_call);
fabCall.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
adapter.add(generateData());
}
});
list = view.findViewById(R.id.list);
adapter = new ListItemHelper(getContext(), new ArrayList<ListItems>());
list.setAdapter(adapter);
}
private ListItems generateData() {
return new ListItems(R.drawable.ic_launcher_background,"Call","Shortcut added");
}
you need to notify the adapter that your list is changed and there is a new item
add this :
adapter.notifyDataSetChanged();
after
adapter = new ListItemHelper(getActivity(),generateData());
and this will fix your problem
why it was working after clicking twice ?
it was worked when you click twice because at the first time you will add new item to the list and initialize a new adapter
at this line -> adapter = new ListItemHelper(getActivity(),generateData());
and the second time when you click again
you set the new adapter to the list here -> list.setAdapter(adapter);
and this will connect the new internalized adapter with the new items to the list
you code should look like this to fix the problem
fabCall.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
list = (ListView) getActivity().findViewById(R.id.list);
adapter = new ListItemHelper(getActivity(),generateData());
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
I just created a listview and I can see all the rows at my listview exept to the first one. anyone got any idea why this is happend. my adapter code is:
public class ChatAdapter extends ArrayAdapter<Message> {
public ChatAdapter(Context context, int resource, List<Message> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.chat_raw, null);
}
Message message = getItem(position);
Log.d("GET VIEW MESSAGE: ", message.getText());
if (message != null) {
TextView tvName = (TextView) v.findViewById(R.id.tvChatName);
TextView tvMessage = (TextView) v.findViewById(R.id.tvChatMessage);
if (tvName != null) {
tvName.setText(message.getUserName());
}
if (tvMessage != null) {
tvMessage.setText(message.getText());
}
}
return v;
}
}
I must say that at line: Log.d("GET VIEW MESSAGE: ", message.getText()); I see all the messages and also the 1st one but at the listview I don't see the 1st one.
edit:
Just change the code according to what you seggest but I still have the same problem, I can't see the 1st row. my adapter code is:
public class ChatAdapter extends ArrayAdapter<Message> {
private Context context;
public ChatAdapter(Context context, int resource, List<Message> items) {
super(context, resource, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder=null;
if(convertView==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_raw, null);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Message message = getItem(position);
if(message!=null) {
viewHolder.tvMessage.setText(message.getText());
viewHolder.tvName.setText(message.getUserName());
}
return row;
}
public class ViewHolder {
TextView tvName;
TextView tvMessage;
public ViewHolder(View view) {
tvName = (TextView) view.findViewById(R.id.tvChatName);
tvMessage = (TextView) view.findViewById(R.id.tvChatMessage);
}
}
}
and my code is:
public class ChatFragment extends Fragment {
private ListView lvChat;
private Button btChatSend;
private EditText etChatMessage;
private ArrayList<Message> alMessage;
private int groupID, userId;
private String userName;
private RequestQueue requestQueue;
private Gson gson;
public ChatFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
alMessage = new ArrayList<>();
groupID = ((DrawAndChat) getActivity()).getGroupId();
userName = ((DrawAndChat) getActivity()).getUserName();
userId = ((DrawAndChat) getActivity()).getUserId();
requestQueue = Volley.newRequestQueue(getActivity());
getAllMessages();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chat_fragment, container, false);
lvChat = (ListView) view.findViewById(R.id.lvChat);
etChatMessage = (EditText) view.findViewById(R.id.etChatMessage);
btChatSend = (Button) view.findViewById(R.id.btChatSend);
lvChat.setAdapter(new ChatAdapter(getActivity(), R.layout.chat_raw, alMessage));
btChatSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
return view;
}
I have an ArrayList with tree elements in it (icon, text(name), text(phonenumber)).
I want to do two things,
1) make whole one element of list clickable
2) make phone call to that number onclick
Now I know I need to use onclicklistener but how do implement it to my code? My main and adapter
public class MainActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_item);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData() {
ArrayList<Model> models = new ArrayList<Model>();
// here are elements of the arraylist header & next are list's elements
models.add(new Model("[text]"));
models.add(new Model(R.drawable.[icon], "[text]", "**[text(number)]**"));
models.add(new Model(R.drawable.[icon2], "[text2]", "**[text(number2)]**"));
return models;
}
}
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.target_item, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.target_item, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
rowView = inflater.inflate(R.layout.group_header_item, parent, false);
TextView titleView = (TextView) rowView.findViewById(R.id.header);
titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Try this-
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
makeCall("Phone Number goes here..");
}
});
public void makeCall(String callTo) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + callTo));
startActivity(callIntent);
}
In you MyAdapter.class to make change like
rowview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
// hear set your array position vise set mobile nmber
startActivity(callIntent);
}
});
I was having some problem when trying to refresh the items in list view after the button was triggered. Here is how I populate the listview onCreate:
public class EventChat extends Fragment {
Context context;
View eventChat;
String userID, eventID;
private ListView listview;
public ArrayList<EventComment> _commentlist = new ArrayList<EventComment>();
TextView txtDisplayCommentBy, txtDisplayDateTime, txtDisplayCommentDesc,
txtEventChat;
Button btnChatSubmit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
eventChat = inflater.inflate(R.layout.event_chat, container, false);
context = getActivity();
listview = (ListView) eventChat.findViewById(R.id.listview);
txtEventChat = (TextView) eventChat.findViewById(R.id.txtEventChat);
btnChatSubmit = (Button) eventChat.findViewById(R.id.btnChatSubmit);
btnChatSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onSubmitChatClicked();
}
});
Intent i = getActivity().getIntent();
_commentlist = (ArrayList<EventComment>) i
.getSerializableExtra("eventCommentObj");
Event eventModel = (Event) i.getSerializableExtra("eventObj");
userID = "Gab";
eventID = eventModel.getEventID();
listview.setAdapter(new ListAdapter(getActivity()));
return eventChat;
}
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
return _commentlist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.eventchat_listview_row,
null);
viewHolder = new ViewHolder();
viewHolder.txt_dcommentBy = (TextView) convertView
.findViewById(R.id.txtDisplayCommentBy);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_dcommentBy.setText(_commentlist.get(position)
.getCommentBy().trim());
return convertView;
}
}
private class ViewHolder {
TextView txt_dcommentBy;
TextView txt_ddateTime;
TextView txt_dcommentDesc;
}
}
When my button was triggered and insert a new record into database, at the same time, I wanted the list view items to be refreshed:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
new CreateCommentAsyncTask(context).execute(commentModel);
txtEventChat.setText("");
}
However, it does not refresh. Any ideas?
Thanks in advance.
Well this looks pretty straightforward.
First make your adapter a class member, so you can access it later:
private ListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mAdapter = new ListAdapter(getActivity();
listview.setAdapter(mAdapter);
...
}
Then, when you submit the item, also add it to your ArrayList and update your adapter:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
// Add the new element to your DB
new CreateCommentAsyncTask(context).execute(commentModel);
// Add the new element to your current ArrayList
_commentlist.add(commentModel)
// Update theListView, by updating the adapter
mAdapter.notifyDataSetChanged();
txtEventChat.setText("");
}
EDIT:
Little more explanation:
When your fragment is created you are passed an array of EventComment items. I guess these are the elements from your DB. When you update the database, however, your ArrayList won't get updated, unless you reload the whole fragment. That's why you add the item to the DB, and to the list manually, and with notifyDataSetChanged, you force your adapter to update the ListView.
You cant do listview.setAdapter(new ListAdapter(getActivity())); to achieve this. You should create an instance of adapter and call adapter.add + adapter.notifyDataSetChanged
This is a very good tutorial :
http://www.vogella.com/tutorials/AndroidListView/article.html
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html