setText Method from onClick Method in Android - java

I am very new to Java and have encountered a problem. I have set up a TextView and want to call the setText method when a button is clicked from my dialog. This TextView is set up in my main activity. I have not initialized it as static as this produces an error. The line of code in question is - Tabs.total.setText("PRINTING TO TEXT VIEW"); I want this to set the content of my TextView defined in my class Tabs.
Variable total is defined like this -
TextView total = (TextView) findViewById(R.id.total_view);
I have looked a lot for some material on this problem but have failed to find a solution so far. I hope somebody can help. Thanks!!
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.scrollergrid, null);
final TextView tv = (TextView)v.findViewById(R.id.icon_text);
tv.setTag(pos);
tv.setText(mItems[pos]);
TextView price = (TextView)v.findViewById(R.id.price_text);
price.setText("$" + Prices[pos]);
pos += 1;
final ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
iv.getLayoutParams().height = 150;
iv.getLayoutParams().width = 150;
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageResource(mThumbIds[position]);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
id = tv.getTag();
System.out.println(mItems[(Integer) id] + " $" + Prices[(Integer) id]);
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertdialog);
dialog.setTitle(mItems[(Integer) id]);
ImageView dialogImage = (ImageView) dialog.findViewById(R.id.alert_image);
dialogImage.setImageResource(mThumbIds[(Integer) id]);
TextView itemDescription = (TextView) dialog.findViewById(R.id.item_description);
itemDescription.setText("A nice little piece of food. Good for all the family. Full of flavour!!");
TextView itemPrice = (TextView) dialog.findViewById(R.id.item_price);
itemPrice.setText("$" + Prices[(Integer) id]);
Button goBack = (Button) dialog.findViewById(R.id.go_back);
goBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
Button order = (Button) dialog.findViewById(R.id.order);
order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Tabs.Order.add(mItems[(Integer) id] + " " + Prices[(Integer) id]);
System.out.println(Tabs.Order);
Tabs.total.setText("HIIII");
dialog.cancel();
}
});
dialog.show();
}
});
}
else
{
v = convertView;
}
return v;
}
}

I think what you want to do is make your own onClickListener().
Check out this solution: How to pass parameters to OnClickListener?
And just pass in your TextView to the constructor.

You have two problems:
Using static variables for storing views is not recommended at all (memory leaks). You should simply put the reference either as a parameter to the function or as a field.
On the "else" part, you didn't update the variable "v" to have the new data being shown, only upon creation of the view you put data into it.

Related

Buttons inside GridView are not getting proper Id

I am designing a chess Board application and I am using a gridview for storing 64 buttons and assigning id to them starting from 0 to 63. But the ids are starting from 2 instead of 0, I can't understand why that is happening.
I am using ButtonAdapter class I made and the following is its getView() method and I set text of each button same as its id to make sure they are getting correct ids.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
Button button;
if(view == null){
button = new Button(mContext);
}else{
button = (Button)view;
}
button.setId(mIndex);
button.setText(button.getId()+"");
button.setTextSize(5);
button.setPadding(0,0,0,0);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, view.getId()+"", Toast.LENGTH_SHORT).show();
}
});
mIndex++;
return button;
}
mIndex is initialized to 0 in my constructor like following
private Context mContext;
private int mIndex;
public ButtonAdapter(Context context){
mContext = context;
mIndex = 0;
}
and the screenshot of result I am getting is below
Please help, I am a beginner. Sorry for any mistakes, thanks in advance.
Don't use mIndexvariable and increment because it will create issue when you will scroll.
You can use adapter position instead of mIndex.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
Button button;
if(view == null){
button = new Button(mContext);
}else{
button = (Button)view;
}
button.setId(i);
button.setText(String.valueOf(i));
button.setTextSize(5);
button.setPadding(0,0,0,0);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, view.getId()+"", Toast.LENGTH_SHORT).show();
}
});
return button;
}
you can set the tag like this
button.setTag(Integer.valueOf(position));
and get that id by
Integer position = (Integer)view.getTag();

Flip Animation not working properly in GridView after onItemClick

I have A grid view. I have A row.xml, which I am inflating in Adapter class. My row xml has two layout (One is visible and another is invisible.) I am doing flip animation. As I click on the any item of gridview then flip animation is happening, and I am doing visible the hided layout, and hiding that visible layout.
The animation is working perfectly. But the issue is that as I am clicking on any item, and scrolling other items also flipping. So as I realize that I am not getting the specific position.
I tried the following code.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
final RecordHolder holder = new RecordHolder();
animation1 = AnimationUtils.loadAnimation(context, R.anim.to_middle);
animation2 = AnimationUtils.loadAnimation(context, R.anim.from_middle);
if (convertView == null) {
row = View.inflate(context, R.layout.row_phone_and_tablet1, null);
} else {
//row = View.inflate(context, R.layout.row_phone_and_tablet1, null);
row = convertView;
}
holder.frontImage = (ImageView) row.findViewById(R.id.myimage_imgvw);
holder.frontMobileName = (TextView) row.findViewById(R.id.name_txtvw);
holder.frontPrice = (TextView) row.findViewById(R.id.price_txtvw);
holder.backMobileName = (TextView) row
.findViewById(R.id.tv_device_name);
holder.descOne = (TextView) row.findViewById(R.id.tv_desc_first);
holder.descTwo = (TextView) row.findViewById(R.id.tv_desc_second);
holder.descThree = (TextView) row.findViewById(R.id.tv_desc_third);
holder.descFour = (TextView) row.findViewById(R.id.tv_desc_fourth);
holder.ccEmi = (TextView) row.findViewById(R.id.tv_price_ccemi);
holder.financeEmi = (TextView) row.findViewById(R.id.tv_price_finance);
holder.frontlayout = (LinearLayout) row.findViewById(R.id.frontlayout);
holder.backlayout = (LinearLayout) row.findViewById(R.id.backlayout);
holder.viewdetails = (Button) row.findViewById(R.id.viewdetails);
holder.tv_front_inr = (TextView) row.findViewById(R.id.tv_front_inr);
holder.tv_description = (TextView) row
.findViewById(R.id.tv_description);
holder.tv_price_ccemi_inr = (TextView) row
.findViewById(R.id.tv_price_ccemi_inr);
holder.tv_ccemi_price = (TextView) row
.findViewById(R.id.tv_ccemi_price);
holder.tv_price_finance_inr = (TextView) row
.findViewById(R.id.tv_price_finance_inr);
holder.tv_financeemi_price = (TextView) row
.findViewById(R.id.tv_financeemi_price);
holder.parentLayout = (LinearLayout) row
.findViewById(R.id.parentLayout);
final PhoneAndTabletItem phoneAndTableItem = data.get(position);
holder.viewdetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ViewPhoneInformation.class);
i.putExtra("SKU_CODE", phoneAndTableItem.getSku_code());
context.startActivity(i);
}
});
// row.setTag(holder);
holder.frontMobileName.setText(phoneAndTableItem.getModel_name());
holder.frontPrice.setText(phoneAndTableItem.getCc_emi());
holder.backMobileName.setText(phoneAndTableItem.getModel_name());
holder.descOne.setText(phoneAndTableItem.getKey_feat_1());
holder.descTwo.setText(phoneAndTableItem.getKey_feat_2());
holder.descThree.setText(phoneAndTableItem.getKey_feat_3());
holder.descFour.setText(phoneAndTableItem.getKey_feat_4());
holder.ccEmi.setText(phoneAndTableItem.getCc_emi());
holder.financeEmi.setText(phoneAndTableItem.getFinance_emi());
holder.frontMobileName.setTypeface(tvHalvetica);
holder.frontPrice.setTypeface(tvHalvetica);
holder.backMobileName.setTypeface(tvHalvetica);
holder.descOne.setTypeface(tvHalvetica);
holder.descTwo.setTypeface(tvHalvetica);
holder.descThree.setTypeface(tvHalvetica);
holder.descFour.setTypeface(tvHalvetica);
holder.ccEmi.setTypeface(tvHalvetica);
holder.financeEmi.setTypeface(tvHalvetica);
holder.tv_front_inr.setTypeface(tvHalvetica);
holder.tv_description.setTypeface(tvHalvetica);
holder.tv_price_ccemi_inr.setTypeface(tvHalvetica);
holder.tv_ccemi_price.setTypeface(tvHalvetica);
holder.tv_price_finance_inr.setTypeface(tvHalvetica);
holder.tv_financeemi_price.setTypeface(tvHalvetica);
// here we are rotating the LinearLayout...
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setTag(position);
// Start Array Check...
Toast.makeText(context, "onClick id: " + v.getTag(), Toast.LENGTH_SHORT).show();
if (selected_views.contains((Integer) v.getTag())) {
holder.frontlayout.clearAnimation();
holder.frontlayout.setAnimation(animation1);
holder.frontlayout.startAnimation(animation1);
HashSet hs = new HashSet();
hs.addAll(selected_views);
selected_views.clear();
selected_views.addAll(hs);
selected_views.remove((Integer) v.getTag());
notifyDataSetChanged();
isBackOfCardShowing = true;
} else {
if (selected_views.size() == 0) {
holder.frontlayout.clearAnimation();
holder.frontlayout.setAnimation(animation1);
holder.frontlayout.startAnimation(animation1);
selected_views.add((Integer) v.getTag());
notifyDataSetChanged();
array_size = selected_views.size();
isBackOfCardShowing = false;
}
else {
holder.frontlayout.clearAnimation();
holder.frontlayout.setAnimation(animation1);
holder.frontlayout.startAnimation(animation1);
selected_views.add((Integer) v.getTag());
notifyDataSetChanged();
isBackOfCardShowing = false;
}
}
// End Array Check...
animation1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
if (isBackOfCardShowing) {
holder.frontlayout.setVisibility(View.VISIBLE);
holder.backlayout.setVisibility(View.GONE);
// holder.frontImage.setImageResource(R.drawable.accesories_dashboard);
} else {
holder.backlayout.setVisibility(View.VISIBLE);
holder.frontlayout.setVisibility(View.GONE);
// holder.frontImage.setImageResource(R.drawable.vas_dashboard);
}
holder.frontlayout.clearAnimation();
holder.frontlayout.setAnimation(animation2);
holder.frontlayout.startAnimation(animation2);
}
});
}
});
holder.parentLayout.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String inserted="";
final String SKV_CODE = phoneAndTableItem.getSku_code().toString();
handler.open();
inserted = handler.insertData(phoneAndTableItem.getModel_name(),
phoneAndTableItem.getKey_feat_1(),
phoneAndTableItem.getKey_feat_2(),
phoneAndTableItem.getKey_feat_3(),
phoneAndTableItem.getKey_feat_4(),
phoneAndTableItem.getCc_emi(),
phoneAndTableItem.getFinance_emi(),
SKV_CODE);
handler.close();
if (inserted.equals("inserted")) {
Toast.makeText(context, " Added to Shortlist " , Toast.LENGTH_SHORT).show();
} else if(inserted.equals("error")){
Toast.makeText(context, " Already present in Shortlist " , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, " Try again " , Toast.LENGTH_SHORT).show();
}
return true;
}
});
return row;
}
static class RecordHolder {
ImageView frontImage;
TextView frontMobileName;
TextView frontPrice;
TextView backMobileName;
TextView descOne;
TextView descTwo;
TextView descThree;
TextView descFour;
TextView ccEmi;
TextView financeEmi;
LinearLayout frontlayout, backlayout, parentLayout;
Button viewdetails;
TextView tv_front_inr, tv_description, tv_price_ccemi_inr,
tv_ccemi_price, tv_price_finance_inr, tv_financeemi_price;
}
This code is showing properly position, but below when I am scrolling, then still I am getting flipped other items also. Please help me.
To get the exact position of item clicked in a GridView, you need to use setOnItemClickListener on your GridView reference, example:
GridView g = (GridView) findViewById(R.id.gridView1);
g.setAdapter(new ImageAdopterShow(this)); // your custom adaptor object goes here
g.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(getBaseContext(), "position of item is " +position, Toast.LENGTH_SHORT).show();
}
});
This is the way i get the position of any item in my GridView. Hope this answers your question.
Your Question is kind of misleading If you can get the item position then you need to change your question for animations not working in GridView properly.

how to visible and hide view in listview item?

I have A listview, and in list view I have A textview. So this text view is visible in every item of listview. So when I click on any Textview then it's visibility mus be gone. But when I'll click on another textview then current must gone and previous must be visible.
In adapter class I tried a lot of things but I did't find the correct way. So how can I get this thing in getView().
holder.floorNo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.floorNo.getId() == v.getId()) {
final int position1 = listView
.getPositionForView((LinearLayout) v
.getParent());
} else {
}
}
});
Here position1 is the current position of click. Pleas help me.
You can set tag of textview as holder.settag(holder.floorNo). on click lister of floorNo get this tag by Textview floorno = (Textview) v.gettag();
Here you will get the clicked textview and add code for visible / invisible .
I don't know Which adapter you are using .If you are using CursorAdapter then in CursorAdapter by overridien method newView() it is possible
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
((TextView) (convertView
.findViewById(R.id.main_body_item_title_second_pics)))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// do your stub here
}
});
}
You can use a textview class member as a "reminder" to know which textview is hidden, something like this :
private View mHiddenView = null
private int mFloorNoId = 0
....
....
holder.floorNo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mHiddenView !=null&&mFloorNoId!=0){
// Show textview that was hidden
mHiddenView.findViewById(mFloorNoId).setVisibility(VISIBLE);
}
// Assign clicked view to hidden one and FloorNo id
mHiddenView = v;
mFloorNoId = holder.floorNo.getId();
// And hide it
mHiddenView.findViewById(mFloorNoId).setVisibility(GONE);
}
});
maintain a list of boolean in your adapter indicating visibility of TextView holder.floorNo.
boolean[] visibilityArray;
in constructor
visibilityArray; = new boolean[ no. Of Elements in your adapter ];
in getView() method
holder.floorNo.setVisibility(visibilityArray[position]);
holder.floorNo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
notifyStateChange(position);
}
});
notifyStateChange(position) method defined as follows
private void notifyStateChange(int position) {
for(int i = 0; i<visibilityArray.length; i++){
visibilityArray[i] = true;
}
visibilityArray[position] = false;
this.notifyDataSetChanged();
}

Cannot refer to a non-final variable LinearLayout inside an inner class defined in a different method

I'm getting this error with my code. I tried to implement suggestions on this topic available here but they are not helping in my case. As i have to pass the LinearLayout and view to be able to delete the view. I can't make LinearLayout ll and view final as they are being passed new values on run time. Any suggestions how can I achieve it? Thanks guys.
My method:
private void addControls(String name, LinearLayout ll, String namevalue) {
View view = new View(this);
//getBaseContext();
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.edit_phone, null);
EditText edit_phone = (EditText) view.findViewById(R.id.txtEditPhone);
edit_phone.requestFocus();
edit_phone.setText(name, TextView.BufferType.NORMAL);
TextView nametext = (TextView) view.findViewById(R.id.NameTextView);
nametext.setText(namevalue, TextView.BufferType.NORMAL);
ImageButton imagedelete = (ImageButton) view.findViewById(R.id.CancelButton);
imagedelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ll.removeView(view);
}
}) ;
ll.addView(view);
}
Method Implementation at onCreate like:
if (memberModel.email.toLowerCase().equals(email))
{
selPer = memberModel.name;
getActionBar().setTitle(selPer);
if(tNumList.size() >= 1)
{
for (int i = 0; i < tNumList.size(); i++)
{
String officePhone = tNumList.get(i).telephoneNumber;
LinearLayout telephoneListView = (LinearLayout) findViewById(R.id.phoneHolder);
addControls(officePhone, telephoneListView, "Phone");
}
}
if(mNumList.size() >= 1)
{
for (int i = 0; i < mNumList.size(); i++)
{
String cellPhone = mNumList.get(i).mobileNo;
LinearLayout mobileListView = (LinearLayout) findViewById(R.id.mobileHolder);
addControls(cellPhone, mobileListView, "Mobile");
}
}
txtOfficeAddress.setText(memberModel.officeAddress, TextView.BufferType.NORMAL);
txtHomeAddress.setText(memberModel.homeAddress, TextView.BufferType.NORMAL);
}
valueTextView.setText(email);
ImageButton imageAddPhone = (ImageButton) findViewById(R.id.AddButton);
imageAddPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout telephoneListView = (LinearLayout) findViewById(R.id.phoneHolder);
addControls(null, telephoneListView, "Phone");
}
}) ;
ImageButton imageAddMobile = (ImageButton) findViewById(R.id.AddButton1);
imageAddMobile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout MobileListView = (LinearLayout) findViewById(R.id.mobileHolder);
addControls(null, MobileListView, "Mobile");
}
}) ;
Any solution with explanation would be helpful.
Just add final qualifiers. final LinearLayout ll and final View view = layoutInflater.... As long as you're not changing references to the objects, you're totally fine to have them final.
Declare your LinearLayout in your main class and use it through out the class.
Solved it ... In case anyone needs solution here it is ....
Declared View view; outside of addControl method and initialized it in addControl method like view = new View(this);.
Then, added in onClick #Override
LinearLayout parent = (LinearLayout)v.getParent();
LinearLayout grandParent=(LinearLayout)parent.getParent();
grandParent.removeView(parent); in place of ll.removeView(view);
That's it all done, nice & fine.

Android OnClickListener to update text within same ListView row

I am making a list view that contains (amongst a few other things) 2 ImageViews and a TextView. The two ImageViews are plus and minus icons, when they are pressed, they need to update the number inside the TextView. They also need to trigger code that will update the sum of the TextViews, below the ListView.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.basket_item, null);
holder.plus = (ImageView) convertView.findViewById(R.id.count_add);
holder.minus = (ImageView) convertView.findViewById(R.id.count_minus);
holder.counter = (TextView) convertView.findViewById(R.id.text_counter);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.id = position;
holder.counter.setId(position);
holder.counter.setText(count[position]);
holder.plus.setId(position);
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (count[id] < 999) {
count[id]++;
totalcount++;
}
}
});
holder.minus.setId(position);
holder.minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int id = v.getId();
if (count[id] > 1) {
count[id]--;
totalCount--;
}
}
});
return convertView;
}
}
class ViewHolder {
ImageView plus;
ImageView minus;
TextView counter;
int id;
}
I believe, to update the counter in the TextView, I need to somehow get my 'holder' inside the OnClickListner, however, as it is not declared as final, I can't.
Is there an easier way to do this, or am I missing a trick here?
Try implement the notifyDataSetChanged() that calls the getView once again. And after that invalidate the textView. But I am not fully sure about the need to call invalidate() here.
public void onClick(View v) {
int id = v.getId();
if (count[id] > 1) {
count[id]--;
totalCount--;
notifyDataSetChanged();
holder.counter.invalidate();
}
}
});
I am not sure about it.I hope it do. Try to paste this line under the Onclick method itself.
"holder.counter.setText('YOUR TEXT totalcount');"

Categories

Resources