How can I add some view (eg. 10) that created with inflater? - android

How can I add some view or remove that created with inflater?
when I’m going to adding second of view it crached
View view = G.inflater.inflate(R.layout.activity_sector, linearLayout, false);
int i=0;
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (myEditText.getText().toString().equals("") || i >= 10) {
return;
} else {
linearLayout.addView(view);
i++;
}
}
});
imgDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
myEditText.setText("");
linearLayout.removeView(view);
i--;
}
});
LOG : java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

The problem is that you are adding the same inflated view every time. Try the following code instead:
#Override
public void onClick(View arg0) {
if (myEditText.getText().toString().equals("") || i >= 10) {
return;
} else {
View view = G.inflater.inflate(R.layout.activity_sector, linearLayout, false);
linearLayout.addView(view);
i++;
}
}

You can add multiple views by inflating them once the click listener registers a click:
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (myEditText.getText().toString().equals("") || i >= 10) {
return;
} else {
View view = G.inflater.inflate(R.layout.activity_sector, linearLayout, false);
linearLayout.addView(view);
i++;
}
}
});
Then a click on imgDelete object would remove the last view inside the layout.
imgDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
myEditText.setText("");
LinearLayout linearLayout;
// Get total view count
int childCount = linearLayout.getChildCount();
// Remove last view inside the layout
linearLayout.removeViewAt(childCount-1);
i--;
}
});
I believe that's the behaviour you are looking for.

Related

why is my onclick is messing up the code?

I have a button submit_house inside a navdraw that gets a onclick listener inside a different button's (add_house) onclick listener. submit_house is the button that ends the onclick of add_house and after that it gets a new onclick. yet for some reason the first submit_house onclick does not work ( the log command there really doesn't register). why is that?
code in main.java:
building_onclick = new View.OnClickListener() {
#Override
public void onClick(final View v) {
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
mMap.setOnMapClickListener(null);
// this line clears the arraylist
arrayList.clear();
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
building.emptyBuilding();
//the navdraw
buildingViewNavdraw(add_house, houseList);
//launches drawer
// locks drawer from opening from swipes
navDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// If the navigation drawer is not open then open it, if its already open then close it.
if(!navDrawer.isDrawerOpen(Gravity.RIGHT)) navDrawer.openDrawer(Gravity.RIGHT);
else navDrawer.closeDrawer(Gravity.LEFT);
//sets building latlng
building.setLat(point.latitude);
building.setLng(point.longitude);
building.setMarkerId(Double.toString(building.getLat()).replace(".","") + Double.toString(building.getLng()).replace(".",""));
View.OnClickListener add_houseOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: create alert dialog to get apartment number
house.setApartment("1");
houseEditNavdraw(status, activists, familyNameEdit, addressEdit, descriptionEdit, currentStatusEdit, submit_house, add_report);
isHouseUploaded = false;
isInBuilding = true;
house.setType("House");
//copies over content from building to house
house.setLat(building.getLat());
house.setLng(building.getLng());
house.setMarkerId("A" + house.getApartment() + building.getMarkerId());
house.setLocation(building.getLocation());
currentStatusEdit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (currentStatusEdit.getSelectedItem().toString().equals("קשר המשך")){
currentActivistsEdit.setVisibility(View.VISIBLE);
activists.setVisibility(View.VISIBLE);
currentActivists.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.VISIBLE);
} else if (currentStatusEdit.getSelectedItem().toString().equals("לא מעוניינים") || currentStatusEdit.getSelectedItem().toString().equals("מעוניינים")){
currentActivists.setVisibility(View.INVISIBLE);
activists.setVisibility(View.INVISIBLE);
currentActivistsEdit.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.VISIBLE);
} else if (currentStatusEdit.getSelectedItem().toString().equals("לא עונים")) {
currentActivists.setVisibility(View.INVISIBLE);
activists.setVisibility(View.INVISIBLE);
currentActivistsEdit.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.INVISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
// this line adds the data of the apartmnet and puts in your array
arrayList.add(house.getApartment() + ": " + "משפחת " + house.getName());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
//sets the report onClicks
add_report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reportEditNavdraw(reportEdit, reportDateEdit, reportActivistsEdit, submit_report);
submit_report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
houseEditNavdraw(status, activists, familyNameEdit, addressEdit, descriptionEdit, currentStatusEdit, submit_house, add_report);
if (currentStatusEdit.getSelectedItem().toString() == "קשר המשך"){
activists.setVisibility(View.VISIBLE);
currentActivistsEdit.setVisibility(View.VISIBLE);
}
Date date = new Date();
Report rpt = new Report(reportActivistsEdit.getText().toString(), reportEdit.getText().toString(), reportDateEdit.getText().toString());
reportNameList.add(house.getMarkerId() + date.toString().replace(" ", "").replace(":", "").replace("GMT+", "").replace(".",""));
reportList.add(rpt);
lastReport.setVisibility(View.VISIBLE);
lastReport.setText(reportEdit.getText());
reportActivistsTitle.setVisibility(View.VISIBLE);
reportActivists.setVisibility(View.VISIBLE);
reportActivists.setText(reportActivistsEdit.getText());
reportDateTitle.setVisibility(View.VISIBLE);
reportDate.setVisibility(View.VISIBLE);
reportDate.setText(reportDateEdit.getText());
reportEdit.setVisibility(View.INVISIBLE);
reportDateEdit.setVisibility(View.INVISIBLE);
reportActivistsEdit.setVisibility(View.INVISIBLE);
submit_report.setVisibility(View.INVISIBLE);
reportDateEdit.setText("");
reportActivistsEdit.setText("");
reportEdit.setText("");
}
});
}
});
submit_house.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO: add safeguards against partial input
//sets data for "blank" drawer
familyName.setText(familyNameEdit.getText());
familyNameEdit.setVisibility(View.INVISIBLE);
familyName.setVisibility(View.VISIBLE);
address.setText(addressEdit.getText());
addressEdit.setVisibility(View.INVISIBLE);
address.setVisibility(View.VISIBLE);
description.setText(descriptionEdit.getText());
descriptionEdit.setVisibility(View.INVISIBLE);
description.setVisibility(View.VISIBLE);
currentStatusEdit.setVisibility(View.INVISIBLE);
currentStatus.setText(currentStatusEdit.getSelectedItem().toString());
currentStatus.setVisibility(View.VISIBLE);
if (currentStatusEdit.getSelectedItem().toString() == "קשר המשך"){
currentActivists.setText(currentActivistsEdit.getText());
currentActivistsEdit.setVisibility(View.INVISIBLE);
currentActivists.setVisibility(View.VISIBLE);
activists.setVisibility(View.VISIBLE);
house.setActivists(currentActivists.getText().toString());
}
submit_report.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.INVISIBLE);
currentStatusEdit.setSelection(0, false);
//setting all the values to house
house.setName(familyName.getText().toString());
house.setAddress(address.getText().toString());
house.setDescription(description.getText().toString());
house.setStatus(currentStatus.getText().toString());
//upload reports to db
if (reportNameList.size() != 0){
for (int i = 0; i < reportNameList.size(); i++){
mDatabase.child("reports").child(reportNameList.get(i)).setValue(reportList.get(i));
}
//sets the report list to the house
house.setReport(reportNameList);
house.setLatestReport(reportNameList.get(reportNameList.size() - 1));
//clears the lists for next use
reportNameList.clear();
reportList.clear();
}
mDatabase.child("houses").child(house.getLocation()).child(house.getMarkerId()).setValue(house);
house.emptyHouse();
isHouseUploaded = true;
building.addHouse(house.getMarkerId());
Log.d("here", building.getHouses().toString());
emptyNavdraw();
buildingViewNavdraw(add_house, houseList);
}
});
}
};
add_house.setOnClickListener(add_houseOnClick);
add_houseOnClick.onClick(v);
submit_house.setVisibility(View.VISIBLE);
add_house.setVisibility(View.INVISIBLE);
submit_house.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.child("houses").child(building.getLocation()).child("B" + building.getMarkerId()).setValue(building);
LatLng latLng = new LatLng(building.getLat(), building.getLng());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.building15x15)));
marker.setTag(building.getMarkerId());
building.emptyBuilding();
submit_house.setVisibility(View.INVISIBLE);
add_house.setVisibility(View.VISIBLE);
submit_house.setOnClickListener(null);
}
});
}
});
}
};
Implement your activity with View.OnClickListener interface.
It will implement a method with name onClick().
Now add this line in onCreate() method : submit_house.setOnClickListener(this);
And you can perform your work in onClick() as
public void onClick(View v)
{
if(v.id==R.id.submit_house)
{
//
}
}
But you cannot perform two different functions on a single button. For that
you have to use internal variable to identify the case.

How to use horizontal view pager inside recycler view

I want to use viewpager inside recycler view and set data on pager from api.
For more details, i'm adding my code in question.
My Code is
public void onBindViewHolder(final worksheetAdapter.CustomViewHolder holder, final int position) {
final int a = position; rec_worksheet.setTag(position);
Set text on TextView
holder.question.setText(userlist.get(position).get("ques"));
holder.question.startAnimation(animFadein);
holder.tvans1.setText(userlist.get(position).get("ans1"));
holder.tvans1.startAnimation(animFadein);
holder.tvans2.setText(userlist.get(position).get("ans2"));
holder.tvans2.startAnimation(animFadein);
holder.tvans3.setText(userlist.get(position).get("ans3"));
holder.tvans3.startAnimation(animFadein);
holder.tvans4.setText(userlist.get(position).get("ans4"));
holder.tvans4.startAnimation(animFadein);
holder.submitbtn.setVisibility(View.GONE);
if(position == userlist.size() - 1){
holder.submitbtn.setVisibility(View.VISIBLE);
}
holder.queNo.setText("Question No "+String.valueOf(position+1));
holder.tvTotalQue.setText("Total Ques. "+String.valueOf(userlist.size()));
holder.tvSubName.setText(userlist.get(position).get("subject_name"));
holder.submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submit();
}
});
Check if first answer is equals to correct answer
holder.llAns1.setTag(position);
holder.llAns1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getTag(position);
holder.llAns1.setBackgroundResource(R.drawable.que_correct_back);
holder.llAns2.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns3.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns4.setBackgroundResource(R.drawable.round_strock_green);
allAns.add(userlist.get(position).get("ans1"));
correctans = userlist.get(position).get("correctans");
if(holder.tvans1.getText().toString().equals(correctans)){
CorrectAns.add(userlist.get(position).get("ans1"));
}else {
try {
wrongAns.add(userlist.get(position).get("ans1"));
CorrectAns.remove(position);
}catch (IndexOutOfBoundsException e){}
}
}
});
Check if secound answer is equals to correct answer
holder.llAns2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.llAns2.setTag(position);
holder.llAns2.setBackgroundResource(R.drawable.que_correct_back);
holder.llAns1.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns3.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns4.setBackgroundResource(R.drawable.round_strock_green);
correctans = userlist.get(position).get("correctans");
if(holder.tvans2.getText().equals(correctans)){
CorrectAns.add(userlist.get(position).get("ans2"));
}else {
try {
wrongAns.add(userlist.get(position).get("ans2"));
CorrectAns.remove(correctans);
}catch (IndexOutOfBoundsException e){}
}
}
});
Check if third answer is equals to correct answer
holder.llAns3.setTag(position);
holder.llAns3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.llAns3.setBackgroundResource(R.drawable.que_correct_back);
holder.llAns2.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns1.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns4.setBackgroundResource(R.drawable.round_strock_green);
correctans = userlist.get(position).get("correctans");
if(holder.tvans3.getText().equals(correctans)){
CorrectAns.add(userlist.get(position).get("ans3"));
}else {
try {
wrongAns.add(userlist.get(position).get("ans3"));
CorrectAns.remove(correctans);
}catch (IndexOutOfBoundsException e){}
}
}
});
Check if forth answer is equals to correct answer
holder.llAns4.setTag(position);
holder.llAns4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.llAns4.setBackgroundResource(R.drawable.que_correct_back);
holder.llAns3.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns2.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns1.setBackgroundResource(R.drawable.round_strock_green);
correctans = userlist.get(position).get("correctans");
if(holder.tvans4.getText().equals(correctans)){
CorrectAns.add(userlist.get(position).get("ans4"));
Log.d("corrAns1",String.valueOf(CorrectAns));
}else {
try {
wrongAns.add(userlist.get(position).get("ans1"));
CorrectAns.remove(correctans);
}catch (IndexOutOfBoundsException e){}
Log.d("corrAns2",String.valueOf(CorrectAns));
}
}
});
}
You cannot use a viewpager inside a recyclerview. If you want to use horizontal swiping inside a recyclerview then you will have to use a recyclerview inside a recyclerview. This child recyclerview will be have a horizontal layout.
This question precisely addresses that.
For the 2nd issue:
Add the following lines
holder.llAns2.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns1.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns3.setBackgroundResource(R.drawable.round_strock_green);
holder.llAns4.setBackgroundResource(R.drawable.round_strock_green);
below this line:
if(position == userlist.size() - 1){
holder.submitbtn.setVisibility(View.VISIBLE);
}
for 3rd issue:
//add this below your adapter class
private ArrayList selectedOptions;
in your onbindviewholder add this below holder.llAns4.setBackgroundResource(R.drawable.round_strock_green)
if(selectedOptions.get(position) != null){
switch (selectedOptions.get(position)){
case 1:
holder.llAns1.setBackgroundResource(R.drawable.que_correct_back);
break;
case 2:
holder.llAns2.setBackgroundResource(R.drawable.que_correct_back);
break;
case 3:
holder.llAns3.setBackgroundResource(R.drawable.que_correct_back);
break;
case 4:
holder.llAns4.setBackgroundResource(R.drawable.que_correct_back);
break;
}
}
I have answered 3 things now. Please ask new stackoverflow question for further issues.

How can I optimize the performance of opening an Android fragment?

I have created an 800 xml layout and a Fragment class, but opening a fragment with a button click takes too long.
Can anyone help me optimize the following code sample?
View lesson655 = (View) getActivity().findViewById(R.id.txtlesson655);
lesson655.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i;
pager.setCurrentItem(0);
for (i = 1; i <= 655; i++) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
}
}
});
If you don't need to go step by step through every Item you can do it this way:
View lesson655 = (View) getActivity().findViewById(R.id.txtlesson655);
lesson655.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pager.setCurrentItem(655);
}
});

Android GridView first button not working

I am having weird problems with Android GridView. I create a 3x4 grid and insert buttons into that grid. I want the background of the button to change when the user clicks that button. And this is working just fine for all buttons except the first one (the one with index 0 - top left). OnClick event listener doesn't fire at all for that button no matter what I do.
Here is the code where I create the view:
public View getView(int position, View convertView, ViewGroup parent) {
Button imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.w("NOVO", "narejena nova celica");
imageView = new Button(mContext);
imageView.setPadding(8, 8, 8, 8);
} else {
Log.w("STARO", "stara celica");
imageView = (Button) convertView;
}
imageView.setEnabled(true);
int visina = parent.getHeight();
int sirina = parent.getWidth();
float dip = mContext.getResources().getDisplayMetrics().density;
float margin = 10*dip;
int view_height = (int)(visina - 3*margin)/4;
int view_width = (int)(sirina - 2*margin)/3;
int view_dim = 0;
if (view_height <= view_width)
view_dim = view_height;
else
view_dim = view_width;
imageView.setLayoutParams(new GridView.LayoutParams(view_dim, view_dim));
imageView.setId(position);
imageView.setOnClickListener(celice.get(position));
/*imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Toast toast = Toast.makeText(mContext, v.getId() + "bla", Toast.LENGTH_SHORT);
//toast.show();
celice.get(v.getId()).celicaVisible(4000);
}});*/
celice.get(position).id = position;
celice.get(position).setButton(imageView);
return imageView;
}
If I replace
imageView = (Button) convertView;
with
imageView = new Button(mContext);
then the onClick() gets fired but the background still doesn't change. All the other buttons are working as expected.
And here is the custom class "Celica" that takes care of the actual work - changing the background...
public class Celica implements OnClickListener {
public boolean odkrit;
public boolean najden;
public int id;
public Drawable slikca1, slikca2;
public Celica par;
private Timer tim;
public Button but;
public Context con;
static int buttonsVisible = 0;
Celica(Drawable s1, Drawable s2) {
this.slikca1 = s1;
this.slikca2 = s2;
}
void celicaVisible(int millis) {
if (odkrit)
return;
Log.w("TEST", "prizganih " + buttonsVisible);
if (buttonsVisible >= 2)
return;
odkrit = true;
buttonsVisible++;
tim = new Timer();
tim.schedule(new timerDone(), millis);
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca2);
}
});
}
void setButton(Button b) {
but = b;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
class timerDone extends TimerTask {
#Override
public void run() {
if (!najden) {
odkrit = false;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
buttonsVisible--;
tim.cancel();
}
}
#Override
public void onClick(View v) {
celicaVisible(4000);
}
}
In Android, ID of any View must be non zero and non negative number. means View ID should be > 0. and there is problem, when you are setting ID to the Button like
imageView.setId(position)
here ID of a button will be zero when position is zero(means first item). may be due to this, First Button's OnClickListener is not getting fired...try setting a ID that is greater than zero to Button and try once...
you can write like
imageView.setId(position+1) to ensure ID > 0
I actually figured it out. Everything works if I use the view that gets provided by the onClick() method instead of saving the actual button at the creation of the Celica object.
So basically adding:
but = (Button) v;
to the onClick() method solved the problem.

why parent view and child view are receiving onclickevent

I have a parent view LinearLayout i have added a child view TextView, But whenever i click on childview why parentview is also clicked. What i want is to differentiate whether only parent has been clicked and only childview is clicked.
LinearLayout rlmain = (LinearLayout)findViewById(R.id.linearLayout1);
rlmain.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
}
});
TextView tv = (TextView )findViewById(R.id.TextViewLayout1);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
}
});
then try to implement View.OnClickListener in yout Activity first, then try to override
#Override
public void onClick(View v){
if(v.getId().equals(R.id.linearLayout1) {
//do ur stuffs
} else {
//do your stuffs
}
Hope it will help you. :)
In android, ViewGroups (i.e. all layouts by inheritance) use the property (and corresponding xml attribute ) : addStatesFromChildren
If set, the parent will just be set in the very same state as one of his children view.
try this code...
LinearLayout rlmain = (LinearLayout)findViewById(R.id.linearLayout1);
rlmain.setOnClickListener(this);
TextView tv = (TextView )findViewById(R.id.TextViewLayout1);
tv.setOnClickListener(this)
#Override
public void onClick(View v){
switch(v.getId()) {
case R.id.TextViewLayout1:
//do ur stuffs
break;
case R.id.linearLayout1:
//do ur stuffs
break;
}
}

Categories

Resources