I have a Toolbar and an item (add) which, when clicked, adds a view in listView below. However, the onOptionsItemSelected gives you the effect of a single click so it only adds one view, and in my case, I need multiple views, thus multiple clicks are required. How do I set up everything so that the item behaves as an onClickListener rather than a single click?
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addButton){
final TextView noProject = (TextView) findViewById(R.id.NOPROJECT);
final ArrayList<String> listItems=new ArrayList<String>();
final ListAdapter addAdapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.listFrame, listItems);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(addAdapter);
noProject.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
listItems.add("New Project");
((ArrayAdapter) addAdapter).notifyDataSetChanged();
}
if (id == R.id.addPeople) {
return true;
}
return super.onOptionsItemSelected(item);
}
Android is always listening for menu item clicks. And on click your action will happen, so you'll need to click multiple times anyways if you want this add feature in the menu.
I usually setup my list adapter in onCreate or onCreateView. Once it's established you can do addAdapter.clear() and addAdapter.add(item). You shouldn't need to reference your listitems directly since the ArrayAdapter.add() method is setup to append to that list anyways and then if i'm not mistaken you can get rid of notifyDataSetChange() - I've never had to use this method with any of the default list adapters or the custom adapters I've written. .clear(), .add(), .insert(), and .remove() should be sufficient.
My listview is usually filled out using a for loop. If you want multiple views added then could you just setup a loop instead of waiting/requiring for more clicks?
Maybe I'm not fully understanding the usecase but a basic for loop seems like the answer here.
Edit:
//For Each Loop - "For each individualItem in itemHolder"
listadapter.clear();
for(ItemType individualItem : itemHolder){
listAdapter.add(individualItem.getText());
}
or you can do a traditional for loop
//"For i(index) starting at index 0, run until index < itemHolder.getItemCount() is false"
//for(initialize index variable : condition check : increment after each iteration)
for(int index =0; index<itemHolder.getItemCount(); index++)
{
listAdapter.add(itemHolder.getItemAt(index));
}
Something like that. I made up method names obviously it's going to depend on your data structures.
Related
I have an application that should work on a tablet, and there's a page where a recyclerview is present and in its row item there is 2 edit texts (with numberDecimal as input), the default keyboard shouldn't appear because it's covering a considerable large portion of screen.
I created buttons in the activity to act like the keyboard buttons however the problem is how to make the button from activity to communicate with the edit texts in the adapter.
how can i know that if I press (Button "1") for example that it should display 1 in the focused edittext in the adapter, and how if I pressed "<" or ">" button it should know the previous and next edit texts
please help
I'll provide example in Kotlin, I assume that is what you are using.
So you can simply override the key handling in the parent class like:
Make a method that you call one time from onCreate like:
fun keydown_onClick(){
try{
myActivity.setOnKeyListener { _, keyCode, event ->
if (keyCode == android.view.KeyEvent.KEYS_YOU_CARE_ABOUT) {
//handle it
if(activeViewHolder != null){
var displayText = activeViewHolder.yourEditText.text
keyPressedChar = (char)event.getUnicodeChar()+""
//if it's a special key you care about, then handle it in a when statement or if and pass to your adapter if needed to go to next row for example.
displayText += keyPressedChar
activeViewHolder.yourEditText.text = displayText
}
return#setOnKeyListener true//we've processed it
} else
return#setOnKeyListener false// pass on to be processed as normal
}
}catch (ex: Exception){
A35Log.e(mClassTag, "Error handling onkeydown listener: ${ex.message}")
}
}
Next up is how do you handle it. well you should keep track of the active row. You can do this by creating a callback in your activity that gets notified when a different row is selected or gains focus.
interface IFocusChangeListener {
fun onNewItemFocused(holder: MyApdaterViewHolder, item: DataItem, index: Int)
}
This will be passed into your adapter and used to fire back to your activity class.
//in activity
var activeViewHolder: MyAdapterViewHolder? = null
var activeIndex: Int? = null
var activeItem: DataItem? = null
fun onNewItemFocused(holder: MyAdapterViewHolder, item: DataItem, index: Int){
activeViewHolder = holder
activeIndex = index
activeItem = item
}
//now in your key down event you simply pass through the value to the editText in the activeViewHolder,
So last piece is in the adapter.
//on bind View
create View holder, the usual bloat.
Then when you have your editText you simply add.
var item = currentDataItem
var index = currentDataItemIndex
var viewHolder = currentViewHolder //from onBind
viewHolder.setOnFocusChangeListener(object: View.OnFocusChangeListener{
override fun onFocusChange(v: View?, hasFocus: Boolean) {
if(hasFocus){
mFocusListener?.onNewItemFocused(viewHolder, item, index)
}
}
})
//in adapter you may also need
fun onNextEditTextClicked(item: DataItem, index: Int){
//get next data Item by index + 1 if exist and get it's viewholder.editText and set focus to it, this will automatically trigger the focus event back to the activity
}
fun onPreviousEditTextClicked(item: DataItem, index: Int){
//get next data Item by index - 1 if exist and get it's viewholder.editText and set focus to it, this will automatically trigger the focus event back to the activity
}
Now you have the focused viewholder in your calling activity, you can catch the keys you care to catch, probably all of them. You can pass them in, you should be good to go.
NOTE*
For the record, if you are using modern practices, aka Data Binding, then you should be able to just update a bindable string in your model and it will show up on the screen without having to pass it around. You could also bind the focus to being selected and just update the selected boolean of the models. There are cleaner ways to do this if you use binding. But for now, just helping you without complicating it.
This solution may need tweaked, I just typed it here so could be off a bit, but should mostly get you there.
Happy Coding.
Intiliased the Adapter before clicking the buttons. because, required the instance of your Adapter to perform.
create a method add() in your Adapter
ArrayList<String> dataList = new ArrayList<>();
public void add(String element) {
dataList.add(element);
notifyItemInserted(dataList.size() - 1);//this will update the recyclerview with data inserted
}
from your button click call this method with your Adapter instance
yourAdapter.add(btn1.getText().toString());
Hi I have a listview showing an arraylist, when an item is clicked it is added to another arraylist and displayed in another activity. What is my problem? I want that if an item (eg a dog) I touch once, is added to the second activity, and it shows. But if I were to touch the item (dog) is not added again.
We would say that I want to check if it exists, not add.
I've tried so, but without success.
if (page2 == null)
{
page2 = (ListView) LayoutInflater.from(Local_mostrar_bebidaActivity.this).inflate(R.layout.page_two_viewpager_listview, null);
page2.setAdapter(adapterlistvMenuVINOSespumosos);
page2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
}});
}
page = page2;
break;
Any ideas?
You have:
if (MiPedidoActivity.itemsListVMiPedido.contains( position)){}
else
MiPedidoActivity.itemsListVMiPedido.add(itemsListVMenuVINOSespumosos.get(position));
You are checking if itemsListVMiPedido contains the integer, position, but you are adding itemsListVMenuVINOSespumosos.get(position) to the list. You need to check if the list contains them item, not the index (think of it exactly like what you are trying to do: "do not add item to list if list already contains item). You probably mean something like this (I just made up Item for example, use whatever class your objects are):
Item item = itemsListVMenuVINOSespumosos.get(position);
if (MiPedidoActivity.itemsListVMiPedido.contains(item)) { // <- look for item!
// ... item already in list
} else {
MiPedidoActivity.itemsListVMiPedido.add(item);
}
By the way, as a suggestion, if your item classes have equals() and hashCode() properly implemented, consider a LinkedHashSet (which will preserve insertion order but will not allow duplicates). There are other Set implementations that may be useful too (e.g. TreeSet if your items implement Comparable), depending on your ordering/sorting requirements.
//first i have this method , below is my question
public void addrows(){
TableRow fila;
tabla = (TableLayout)findViewById(R.id.tabla);
TextView txtNombre;
for(int i = 0;i<id;i++){
String x[] = helper.leer();
layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
caja= new CheckBox(this);
fila = new TableRow(this);
fila.setLayoutParams(layoutFila);
txtNombre = new TextView(this);
txtNombre.setId(i);
txtNombre.setTextSize(17);
txtNombre.setText(x[i]);
txtNombre.setGravity(Gravity.LEFT);
// txtNombre.setLayoutParams(layoutTexto);
caja.setText("");
caja.setId(i);
fila.addView(txtNombre);
fila.addView(caja);
tabla.addView(fila);
}
}
i know that when the oncreate() method start the checkboxes objects are created and then i assign an numerical id from 0 to wherever the for cycle stop , but later in the program i need to retrieve what checkboxes were clicked so first i need the id but eclipse wont let me put the numerical id, please help! and sorry for my English i'm a noob in android and the English language
this.CheckBox = (CheckBox)this.findViewById(R.id.?);
As You may read in View class documentation ID should be unique within a tree You search.
You set same id for TextView and Checkbox.
If You know You are going to access them all later after creation keep references to them in array instead of trying to retrieve them later using findViewById.
But even better solution would be to set onClick event listener for them and keep track of checking/unchecking them.
In #HalR's answer You may read how to set onCheckedChanged event listeners for Your checkboxes. Folowing his solution will have an ArrayList of checked checkboxes.
Next step, You have to increment values of correct TextView so You need to couple CheckBoxes and TextViews.
I think best for this would be to set Tag for CheckBox with value of TextView id.
So after user submits You iterate over List of checkboxes, getTag and use it in findViewById to get TextView and update its value.
Id (short for IDentifier) is an integer to uniquely identify elements, You can use it in findViewById to get view elements. You can read more about ID in this answer
Tag is used to associate View element with some extra data as You may read in getTag documentation. It takes as parameter Object type so You set as tag anything not only numbers. In Your case You could set as ChechBox's tag a TextView instead of its id and it will work too.
You are manually setting your id to the index of the row, which is something I don't think I'd do. I'd normally use setTag() to identify my object.
I think it would be easier to use a listener to detect when the checkboxes have been checked, and you can track the changes when the check happens.
use something like this:
In your Activity, create a ArrayList
ArrayList<CheckBox> checkedBoxes = new ArrayList<CheckBox>();
then in your creation:
caja= new CheckBox(this);
caja.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
int index = buttonView.getId();//pulling back the number you set originally, if that is what you like. I would get the tag I had set, and maybe do something here.
//do something in here!
if (buttonView.isChecked()) {
//including this checkbox in the list of checked boxes
checkedBoxes.addObject(buttonView);
} else {
//take it out of the list of checked boxes
checkedBoxes.removeObject(buttonView);
}
}
};
Some info on Id vs Tag
Id is a numeric value that identifies the view in the view hierarchy. If you are using things in your layout, like aligning one view with another, they look for and expect a view with a specific id. So in layout, you'll have android:id="#+id/bigBox" and that will create some number that it associates with bigBox. When you find that view, with findViewById() that is the number it is looking for. When you manually set those numbers, it seems like you are asking for trouble. If you set a view's id to 2, then you should be able to find it with myView = findViewById(2).
Tag is a nicely little object pointer that you can pass along with your view. Quite often it will be a row number:
Integer saveMe = new Integer(i);
checkBox.setTag(saveMe);
Or it can even be a pointer to your original data object that you used to create that row. If you had created each row using a contact, you could use
myRow.setTag(contact)
and later when you clicked on that row, you would just use
contact = (Contact)myRow.getTag()
and you would have your original contact back. Its way cleaner than keeping big arrays of your rows or checkboxes, or whatevers. Just use listeners that detect when you do something, that is a much better way.
Oh, and if you if you do have an onClick(View view) that is triggered by your CheckBox, that view IS your CheckBox.
CheckBox theBoxIJustChecked = (CheckBox)view;
You don't need to look it up with some id. It's right there.
If you want to go this way than you should just do the apposite operation i.e.:
for(int i = 0; i < n; ++i){
...
...(CheckBox))this.findViewById(i);
...
}
It should work for you
However be careful as if you have number of views with the same id inside the view-tree than findViewById(i) can return an unexpected result such as returning the first view in view-tree with given id (it can be not of CheckBox type which can lead to ClassCAstException)
Update in reply to comment
If you want to make some sort of logical connection CheckBox-TextView there are several options:
You can make a sort of function like the following (assuming that there is the limit of CheckBoxes and TextViews quantity):
Code:
private static int CHECK_BOX_MAX_NUMBER = 10000;
public void int getTextVieIdByCheckBoxId(int checkBoxId){
if(checkBoxId >= CHECK_BOX_MAX_NUMBER){
// you can throw an exception here for example
}
return CHECK_BOX_MAX_NUMBER + checkBoxId;
}
And then you should set id's to your TextViews with that function.
checkBox.setId(i);
textView.setId(getTextVieIdByCheckBoxId(i));
....
// add Views to your layout
....
(CheckBox)this.findViewById(i);
TextView)this.findViewById(getTextVieIdByCheckBoxId(i));
or
2.I think there is a little bit more accurate method:
Just use setTag() of CheckBox instances to set appropreate TextView inside in order to create interconnection. In thiscase you have to store all the created checkBoxes in some List or array:
List<CheckBox> checkBoxList = new ArrayList<CheckBox>();
for(int i = 0; i < n; ++i){
...
CheckBox checkBox = new CheckBox();
TextView textView = new TextView();
checkBox.setTag(textView);
checkBoxList.add(checkBox);
}
Then you can achieve what you want like this:
int textBoxListSize = checkBoxList.size();
for(int i = 0; i < textBoxListSize; ++i){
CheckBox checkBox = checkBoxList.get(i);
if(chechkBox.isChecked()){
TextView textView = (TextView)checkBox.getTag();
//do whatever with textView
}
}
Here you don't need to generate id's and worry about collisions which could accure
I'm just starting out in java & android.
Below is my code, to add all the buttons in an activity then hide them.
Question: is their anyway to automatically add all the buttons in the activity without having to list each of them, I have looked at listA.addall but didn't understand how to add the activity as the collection.
The rational for this is I may wish to change the number of buttons and still have the code work.
public void setup2(){
List<Button> listA = new ArrayList<Button>();
listA.add((Button)findViewById(R.id.button1));
listA.add((Button)findViewById(R.id.button2));
listA.add((Button)findViewById(R.id.button3));
listA.add((Button)findViewById(R.id.button4));
listA.add((Button)findViewById(R.id.button5));
for (Button item : listA)
item.setVisibility(View.INVISIBLE);
}
Yes, that is probably the cleanest way of doing it. But if your buttons are all similarly id named (button_1, button_2 etc) You could search via string instead of direct ID reference. The following is an example of fetching a button by string:
int resID = getResources().getIdentifier("button_%i", "id", getPackageName());
Button addButton = (Button) findViewById(resID);
Then you could loop around all your buttons.
Assuming that your buttons are in a view group e,g, LinearLayout:
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v.getClass() == Button.class) {
listA.add(v);
}
}
layout is a reference to the layout containing the buttons.
This simply iterates over each child view in the layout, compares it's class type with Button and adds it to your collection if it is.
why I am not able to refresh/reload my ListView?
I' ve written an app, which read out html-websites, saves the information in a String-Array an present it in my ListView.
But every time I close and re-open the app the new content append to the existing content.
In the first run I get, e. g., "1 2 3 4" and in the second run "1 2 3 4 1 2 3 4" and then " 1 2 3 4 1 2 3 4 1 2 3 4" and so on.
I google a lot and find the methods to clear an ArrayAdapter (aa) and refill it with new data
-> aa.clear() / aa.setModifyDataChanged() / aa.remove(String Object) / aa.add(String)
but every time i call one Method my app does a force close and LogCat shows the exception: java.lang.UnsupportedOperationException.
Why? This really grind my gears. The whole saturday afternoon I try to fix it -without success...
Maybe somebody could help me!?
Here is my code-snippet
public class viewband extends ListActivity
{
private static final int AKTUALISIEREN = 0;
private static ArrayList<String> al = new ArrayList<String>();
static String[] TST;
static ArrayAdapter<String> ad;
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case AKTUALISIEREN:
getIt();
//here a ad.close does a force close
setListAdapter(ad);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getIt();
ad = new ArrayAdapter<String>(this, R.layout.list_item, TST);
setListAdapter(ad);
// here, when I try ad.clear() my app does a force close
ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
public static void getIt ()
{
// Here I get the source-code of the html-site and parse my content
// All necessary Information I write in my String Array TST, declared above in a static way
}
I hope, somebody could help me...
Many thanks and a nice sunday.
You need to back your ArrayAdapter by an ArrayList or List rather than a fixed-size array - the size of a fixed-size array cannot change nor can it be cleared (without re-creating it, which defaults the whole purpose)
So set the content of your adapter to be al rather than TST (on a side note you really need to name your variables with sensible names). Then call al.clear(), al.add(String), to modify the dataset backing the adapter. Once the dataset has been changed call ad.notifyDataSetChanged - this will then cause the list adapter and list to update the display.
Also your adapter should not be static (nor should TST or al probably) -- this will lead to memory leaks since the Adapter holds onto a reference to the current Context. NEVER make anything with a context static (drawables, adapters etc). Unless you know why you want something to be static keep it as a normal variable.
clear TST all time you update your listview