How to remove added views programmatically - java

I have a dialog wherein a user can add EditText and also remove it. I have successfully added EditText programmatically but my code for removing it doesn't work. I'm following this tutorial but in my case setup is inside a dialog.
and also i want to get all the the texts on those EditTexts and store it inside an Array.
This is my code:
public void showSurveyDialog(Context context) {
ImageButton btnAddChoices, btnRemoveChoice;
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.survey_content);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
btnAddChoices = dialog.findViewById(R.id.btn_add_choices);
LinearLayout choiceLayout = dialog.findViewById(R.id.choice_layout);
btnAddChoices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = dialog.getLayoutInflater().inflate(R.layout.choice_item, null);
// Add the new row before the add field button.
choiceLayout.addView(rowView, choiceLayout.getChildCount() - 1);
ImageButton imageButton = dialog.findViewById(R.id.btn_choice_close);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("asdass","ASDASd");
choiceLayout.removeView((View)v.getParent());
}
});
}
});
dialog.show();
}
When pressing btnAddChoices a layout with EditText and Button(for removing) is automatically added to a linear layout. I'am trying to make the remove button to work but it doesn't remove the view.

you can try my add and remove code for references, this can add or remove view programmatically:
private void addressField(View view){
final int[] textCount = {0};
LinearLayout addressLayout = view.findViewById(R.id.address_layout);
addressScroll.removeView(addressLayout);
View layout2 = LayoutInflater.from(view.getContext()).inflate(R.layout.address_text_field
, addressLayout,false);
layout2.setTag("address"+Integer.toString(counter));
addressLayout.addView(layout2);
addressScroll.addView(addressLayout);
ImageView deleteButton = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.delete_address);
TextFieldBoxes addressText = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.address_wrapper);
addressText.setSimpleTextChangeWatcher((theNewText, isError) -> {
if(Objects.equals(theNewText, "")){
textCount[0] = 0;
addressLayout.removeView(layout2);
}
if(theNewText.length() == 1 && textCount[0] == 0){
addressField(view);
ExtendedEditText addressText2 = layout2.findViewWithTag("address"+Integer.toString(counter-1))
.findViewById(R.id.address_text);
addressText2.requestFocus();
counter++;
}
textCount[0]++;
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addressLayout.removeView(layout2);
}
});
}
hope can solve your problems

Related

Android - How to get the currently "focused" object?

I want to let a Button identify which of my TextViews got the current focus. And after that the Button needs to apply changes to the focused TextView.
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
textView11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView11.setBackgroundColor(Color.LTGRAY);
textView11.setFocusableInTouchMode(true);
textView11.requestFocus();
}
});
MaterialButton pb1 = (MaterialButton) findViewById(R.id.pin_button_1);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//1. get the focused textview or scan for the focused textView
//2. apply button function to the focused textView
}
});
So how can i identify here
//1. get the focused textview or scan for the focused textView
which TextView has the focus currently?
I think it might be possible with some help variable but maybe there os another way, because then i still need a onClickListener for each of the 22 TextView
Untested but should work
private TextView hasFocusTextView;
private View.OnFocusChangeListener onFocusChangedListener = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
hasFocusTextView = (TextView) v;
}
};
..
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
//Use same listener on all textview you want to include with the focus logic
textView11.setOnFocusChangeListener(onFocusChangedListener);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasFocusTextView.setText("Changing text of the focused TextView");
}
});
You can simply place these TextView in the same ViewGroup, then just traverse the ViewGroup's child views like this:
for (child in container.children){
if (child.isFocused){
//do your jobs here
}
}
Best way is to use a variable to store which TextView currently has focus.
TextView currentTextView = null;
void initView() {
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
textView11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView11.setBackgroundColor(Color.LTGRAY);
textView11.setFocusableInTouchMode(true);
textView11.requestFocus();
// Set the currentTextView to the currently focused
// this must be used in every focusable textview
currentTextView = (TextView) view;
}
});
MaterialButton pb1 = (MaterialButton) findViewById(R.id.pin_button_1);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//1. get the focused textview or scan for the focused textView
// focused textview is currentTextView
//2. apply button function to the focused textView
// Edit: Check for nullability
if (currentTextView != null) {
// use the variable currentTextView
}
}
});
}

Delete a listview item with a button in it self in android studio

As I am very new to java pls help me on this. I have a custom list view in my main activity and a Custom adapter with it. In my every list item there is a delete button that should delete that item when it clicked. I can not remove data from my arraylist when i am inside my custom adapter. Pls helm me in coding this delete button.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText getItem;
Button AddButton;
Button DellButton;
public static ArrayList<String> myData = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView)
findViewById(R.id.listView);
getItem = (EditText) findViewById(R.id.newItem);
AddButton = (Button) findViewById(R.id.AddButton);
MyAdapter adapter = new MyAdapter(this, myData);
list.setAdapter(adapter);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = getItem.getText().toString();
myData.add(result);
adapter.notifyDataSetChanged();
}
});
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, ArrayList<String> records) {
super(context, 0, records);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
final TextView lst_txt = (TextView) convertView.findViewById(R.id.list_Txt2);
Button plusbut = (Button) convertView.findViewById(R.id.plusbut);
Button minusbut = (Button) convertView.findViewById(R.id.minusbut);
final TextView sum = (TextView) convertView.findViewById(R.id.sum);
Button cal = (Button) convertView.findViewById(R.id.calButton);
Button delete = (Button) convertView.findViewById(R.id.btnDel);
lst_txt.setText(item);
minusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll - 1;
sum.setText(String.valueOf(sum1));
}
});
plusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll + 1;
sum.setText(String.valueOf(sum1));
}
});
cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = sum.getText().toString();
Intent intent = new Intent(getContext(), calll.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("sumFL", s);
getContext().startActivity(intent);
}
});
return convertView;
}
}
Please first try to remove object from list by using the position of item with check the validation with list size and then call notifyItemadapter to update the list view.
Use ViewHolder class for all view like textview, button etc. And initialize them inside the condition
if(convert view==null){
Initialize holder object here and
Inflate your layout and
Initialize button like
holder.deletebutton = convert view.findviewbyid from xml
settag(holder)
}
Again get the holdet using the gettag in
else{
//Here
}
Put All click event and text update etc. Outside of above condition
holder.deletbutton.setonclicklistener{
int pos = view.getag
list.remove(pos)
Notifyadapter here
}
holder.deletebutton.settag(position)

How to add editText and buttons dynamically using LayoutInflater and set a unique id for them?

I am doing adding specifications on the product and I want to that when users click on add_field_btn it will show the XML file contains of two editText with a delete button on the side using the LayoutInflater. But I don't know how to implement the adding of a unique id for every editText that are generated.
Below is my code:
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_products);
backBTN = findViewById(R.id.imageButton);
backBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddProductsActivity.this, StoreHomeActivity.class);
intent.putExtra("userid", userID);
startActivity(intent);
overridePendingTransition(R.anim.mid_to_left, R.anim.right_to_mid);
}
});
}
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.product_specification_item_layout, null);
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
You are on right way; just check this below function that i modified.
int myTagCount=0;
public void onAddField(View v) {
myTagCount++;
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.product_specification_item_layout, null);
TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
tv_delete.setText("Delete");
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parentLinearLayout.removeView(view);
}
});
view.setTag(myTagCount);
parentLinearLayout.addView(view);
}
I use inflater this way. This will also helps you.
For getting value with Tag, check this:
for (int i = 0; i < parentLinearLayout.getChildCount(); i++) {
View view = parentLinearLayout.getChildAt(i);
if (view.getTag().equals(myTagCount)) {
EditText editText = (EditText) view.findViewById(R.id.edt1);
String myText = editText.getText().toString();
break;
}
}

How to move between the elements of recyclerview inside its adapters

I couldn't phrase the question perfectly with my problem, but basically what I want to achieve is this:-
I have recyclerview of items that contains textview for example, when the item is clicked; a custom dialog will show containing the same content of the clicked element.
so far so good, in the same dialog there's two arrow (left & right) at each of its sides, the arrows buttons should navigate between the recyclerview items and update the content according to the new position.
Here's what I did:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position+1;
}
textViewTitle.setText(data.get(position).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position-1;
}
textViewTitle.setText(data.get(position).getTitle());
} });
}});
}
The Result:
When I click on the right arrow it works 100% , but if I click again nothing happens !!
And If click the left arrow at anytime it gives crash with this exception:
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
Is it possible to achieve a loop effect, what I mean is when I reach
the last index and the click again it shows the first index and vice
versa..!
Any help?
It seems the issue is from how you check your click limits. You can try this
Add curPosi as a class member variable
private int curPosi;
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
curPosi = position
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int lastIndex = data.size()-1;
if (lastIndex == curPosi ) { // this prevents the crash, so if the next button is clicked while the last index is showing it will reset and show the first one..!
curPosi = 0;
} else if(curPosi < data.size()) {
curPosi++;
}
textViewTitle.setText(data.get(curPosi).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//same thing here with this "if", when the previous button clicked from the first; it will show the last item..!
if (curPosi == 0) {
curPosi = data.size();
}
if (curPosi > 0) {
curPosi--;
}
textViewTitle.setText(data.get(curPosi).getTitle());
} });
}});
}

Access and edit child view of custom adapter

I have a ListView populated by a custom ArrayAdapter.
The structure of each row is composed by
ImageView
TextView
NumberPicker
ImageButton
Clicking on the ImageButton should show a popup window which contains a color slider and a "ACCEPT" button.
Here is an image that should clarify the layout.
What I would like to do is : by clicking the "ACCEPT" button contained in the popup window, I should retrieve the selected color, set it as background color of the ImageButton and dismiss the popupwindow.
Here is the code :
public View getView(final int position, View convertView, ViewGroup parent) {
_row_view = convertView;
db = new SofosDbDAO(this._ctx);
if(_row_view==null){
// 1. Create inflater
_inflater = (LayoutInflater) _ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_row_view = _inflater.inflate(R.layout.riga_app,parent,false);
}
// 2. Inflate xml layout
_row_view = _inflater.inflate(R.layout.riga_app, parent, false);
// 3. Initialize child views
_iconaapp = (ImageView)_row_view.findViewById(R.id.riga_app_iv);
_nomeapp = (TextView)_row_view.findViewById(R.id.riga_app_tv);
_numerovibrazioni = (NumberPicker)_row_view.findViewById(R.id.riga_app_np);
_colorenotifica = (ImageButton)_row_view.findViewById(R.id.riga_app_ib);
// 4. Set Values
int iconid = _ctx.getResources().getIdentifier(_sofosapps.get(position).get_app_icon(), "drawable", _ctx.getPackageName());
Drawable icon = _ctx.getResources().getDrawable(iconid);
_iconaapp.setImageDrawable(icon);
String appname = _sofosapps.get(position).get_app_name();
_nomeapp.setText(appname);
_numerovibrazioni.setMinValue(0);
_numerovibrazioni.setMaxValue(5);
_numerovibrazioni.setValue(_sofosapps.get(position).get_vibrations());
//Update DB when number picker value gets changed
_numerovibrazioni.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
SofosApp app = _sofosapps.get(position);
app.set_vibrations(newVal);
db.openDb();
db.updateAppVibrations(app);
db.closeDb();
Log.d("DEBUG", "Updated nr of vibrations");
}
});
//Set initial ImageButton background color
_colorenotifica.setBackgroundColor(_sofosapps.get(position).get_color());
//Show popup window on click of ImageButton
_colorenotifica.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_popupcontainer = (ViewGroup)_inflater.inflate(R.layout.color_picker_popup,null);
_puw = new PopupWindow(_popupcontainer,800,600,true);//view,dimensioni e focusable
_btn_applica = (Button) _popupcontainer.findViewById(R.id.color_picker_btn_applica);
_tv_applica_colore = (TextView) _popupcontainer.findViewById(R.id.color_picker_tv);
_tv_applica_colore.setText(_sofosapps.get(position).get_app_name());
_lss = (LobsterShadeSlider)_popupcontainer.findViewById(R.id.color_picker_ls);
_puw.showAtLocation(_popupcontainer, Gravity.CENTER, 20, 50);
Log.d("DEBUG","I clicked on imagebutton and opened my popupwindow");
}
});
//**********************************************************
*********************** CRUCIAL POINT **********************
************************************************************
//Click of accept button inside popupwindow
_btn_applica.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newcolor = _lss.getColor();
String dbg = "color = " + String.valueOf(newcolor);
Log.d("DEBUG", dbg);
_colorenotifica.setBackgroundColor(newcolor);
_puw.dismiss();
_colorenotifica.invalidate();
Log.d("DEBUG", "Cliked accept");
}
});
// 5. retrn rowView
return _row_view;
}
I realize that this approach is not correct as the background image of the imagebutton does not change. Also , for some reason, I fail to create a new popup window for each row : when I click on any image button , the same popup window appears with the textview text set to "Twitter" , the last row.
What is the right way of doing this?
Thank you for the help!
You should change value of color in your array _sofosapps and then call notifydatasetchanged on adapter.
_colorenotifica.setTag(position);
_colorenotifica.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
_popupcontainer = (ViewGroup)_inflater.inflate(R.layout.color_picker_popup,null);
_puw = new PopupWindow(_popupcontainer,800,600,true);//view,dimensioni e focusable
_btn_applica = (Button) _popupcontainer.findViewById(R.id.color_picker_btn_applica);
_tv_applica_colore = (TextView) _popupcontainer.findViewById(R.id.color_picker_tv);
_tv_applica_colore.setText(_sofosapps.get(position).get_app_name());
_lss = (LobsterShadeSlider)_popupcontainer.findViewById(R.id.color_picker_ls);
_puw.showAtLocation(_popupcontainer, Gravity.CENTER, 20, 50);
_btn_applica.setTag(position);
Log.d("DEBUG","I clicked on imagebutton and opened my popupwindow");
}
});
_btn_applica.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newcolor = _lss.getColor();
String dbg = "color = " + String.valueOf(newcolor);
Log.d("DEBUG", dbg);
int position = (int)v.getTag();
_sofosapps.get(position).setColor(dbg);
notifyDataSetChanged();
_puw.dismiss();
}
});
invoke custom dialog on onClick event of _colorenotifica and listen to it's button click events, then get the appropriate item object based on position and apply changes...
.
.
_colorenotifica.setOnClickListener(new View.OnClickListener() {
int mPosition = position;
#Override
public void onClick(View v) {
/**
* invoke custom dialog, add button..
*/
dlg.setButton(AlertDialog.BUTTON_POSITIVE, "Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getItem(mPosition); // apply changes to the item at position `mPosition`
}
});
}
});
.
.

Categories

Resources