I'm new to android and I'm having a hard time finding solutions to my problem on my app.
My app is a wordsearch game that uses tapping on the tiles as an input. This is the code for the onClick() of the dynamic textviews on the tablelayout:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
w.setVisibility(View.VISIBLE);
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor(mColors[randomNum]));
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
//check if answer is in the word grid
if(checkAns(uTxt, list))
{
w.setVisibility(View.GONE);
wC.setText(String.valueOf(Integer.parseInt(wC.getText()+"")-1));
if(Integer.parseInt(wC.getText()+"") == 0){
int newM = minutes*60 + seconds;
dataHelper.insertData(pNameC.getText().toString(), newM, currentDateandTime, Category.leve);
t.cancel();
Context mContext = getApplicationContext();
Activity mActivity = GameScreen.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
// Inflate the custom layout/view
View customView = inflater.inflate(R.layout.gameover,null);
// Initialize a new instance of popup window
PopupWindow mPopupWindow = new PopupWindow(
customView,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
Typeface font = Typeface.createFromAsset(getAssets(), "raw2.ttf");
TextView cattxt = (TextView)customView.findViewById(R.id.catTxt);
String ctg = ti.getText().toString();
cattxt.setTypeface(font);
cattxt.setText(ctg);
Button yesB = (Button) customView.findViewById(R.id.maglaro2);
yesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GameScreen.this, Category.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
Button noB = (Button) customView.findViewById(R.id.hindi);
noB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameScreen.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
mPopupWindow.showAtLocation(table, Gravity.CENTER,0,0);
}
uTxt.setText("");
}
}
});
Now my problem is I want an UNDO Button that will delete the last character on the uTxt and will change back the color of the last touched textView
Does anyone have any ideas on how to do that?
If yes leave a comment, answer, or suggestion below. TIA!
Typical solution for this problem is the usage of the command pattern (excellent for undo redo functionality).
See https://en.wikipedia.org/wiki/Command_pattern
Related
I have a button with the onClick name of checkResult.
public void checkResult(View view){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout myRoot = new LinearLayout(this);
View popupView = layoutInflater.inflate(R.layout.layout_result_popup, myRoot);
final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//what I want to show in the popup
TextView scorePopup = (TextView)findViewById(R.id.score_popup);
scorePopup.setText("Your score: " + score);
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(checkResultButton, 100, -1200);
popupWindow.setFocusable(true);
popupWindow.update();
}
When checkResult button is clicked, layout_result_popup is displayed.
I directly put a button at main activity and use onClick to show popup. So far, I managed to show the popup text in XML. But when I try to set some text to it, my app crashed.
Help please. :)
Try to replace those 2 lines with this:
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView countView = (TextView)findViewById(R.id.count);
countView .setText("Count: " + count+ "/" + totalCount);
}
});
It very likely even works with the first line outside of the runOnUiThread
im trying to build share dialog.
in this share dialog I have facebook,whatsapp,mail and more.
im trying the make the background of every view change on touch to indicate the toch.
so far no problem.
the problem is that I also want to let the user move is finger into other option and when he do that the previous background return to his original color and the new view background changes.
i just cant get the hover event at all, and I couldn't trigger other onTouchEvent as long as the first one is still alive.
this is my code so far:
public class customDialogFragment1 extends DialogFragment {
public customDialogFragment1() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
postShareUrl=getActivity().getResources().getString(R.string.servicePostShareUrl);
id=getArguments().getString("body");
postTitle=getArguments().getString("subject");
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
Dialog dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.share_title_layout, null);
// Set title divider color
TextView txtTitle= (TextView) v.findViewById(R.id.share_title);
Typeface tf = Typeface.createFromAsset(getActivity().getResources().getAssets(),
"fonts/OpenSansHebrew-Bold.ttf");
txtTitle.setTypeface(tf);
View layout=inflater.inflate(R.layout.custom_share_layout_inner,null);
builder.setView(layout);
ImageView facebook= (ImageView) layout.findViewById(R.id.imgFaceebook);
ImageView whatsapp= (ImageView) layout.findViewById(R.id.imgWhatsapp);
ImageView more= (ImageView) layout.findViewById(R.id.imgMore);
ImageView mail= (ImageView) layout.findViewById(R.id.imgMail);
facebook.setOnClickListener(imageClickListener);
whatsapp.setOnClickListener(imageClickListener);
more.setOnClickListener(imageClickListener);
mail.setOnClickListener(imageClickListener);
List activities = getActivity().getPackageManager().queryIntentActivities(sendIntent, 0);
Context context=(Activity)getActivity();
for(int i=0;i<activities.size();i++) {
ResolveInfo appPacageName = (ResolveInfo) activities.get(i);
Log.i("pacageName", appPacageName.toString());
if (appPacageName.toString().contains("com.facebook.composer")) {
shareCheckList[0] = appPacageName;
} else if (appPacageName.toString().contains("whatsapp")) {
shareCheckList[1] = appPacageName;
} else if (appPacageName.toString().contains("mail")) {
shareCheckList[2] = appPacageName;
}
}
dialog.setContentView(layout);
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
window.setLayout(MainActivity.screenWidth-90,350);
return dialog;
}
and this is my ontouch listener :
private View.OnClickListener imageClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,getArguments().getString("subject"));
intent.putExtra(Intent.EXTRA_TEXT,getArguments().getString("body"));
switch (v.getId()){
case R.id.imgFaceebook:
if(!shareCheckList[0].toString().isEmpty()){
intent.setClassName(shareCheckList[0].activityInfo.packageName, shareCheckList[0].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
break;
case R.id.imgWhatsapp:
intent.setClassName(shareCheckList[1].activityInfo.packageName, shareCheckList[1].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
}
break;
case R.id.imgMail:
try{
intent.setClassName(shareCheckList[2].activityInfo.packageName, shareCheckList[2].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
break;
case R.id.imgMore:
CustomDialogFragment2 cdf=new CustomDialogFragment2();
Bundle bundle = new Bundle();
bundle.putString("body",id);
bundle.putString("subject", postTitle);
cdf.setArguments(bundle);
cdf.show(getActivity().getFragmentManager(), "customDialogFragment2");
break;
}
}
};
If I understood right, you should use state list:
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
Just create xml drawable file for every ImageView, and set for each state item with source you need.
I am developing a android App which is totally based on request and response from servlet.I have populate some data in customize Alert-dialog Where i using two thing one is cross button that will delete item from list in alert-dialog and update view of alert dialog , second thing is close button that will suppose to dismiss this alert-dialog. I am showing full coding of my alert-dialog. I calling alert dialog on button click by all these method.
intiliazeOrderListDialog();
showOrderListDialog();
My decleration is as follow
public AlertDialog detailsDialog, orderDialog;
AlertDialog.Builder builder;
Now i am going to post my intiliazeOrderListDialog() block.
public void intiliazeOrderListDialog() {
builder = new AlertDialog.Builder(MainScreen.this);
mContext = getApplicationContext();
inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
orderDialogLayout = inflater.inflate(R.layout.my_order_list,(ViewGroup)findViewById(R.id.order_list_root));
orderList = (ListView) orderDialogLayout.findViewById(R.id.order_list);
ibOrderDelete = (ImageButton)orderDialogLayout.findViewById(R.id.deleteOrder);
tvPrice = (TextView) orderDialogLayout.findViewById(R.id.order_list_total);
tvTaxes = (TextView) orderDialogLayout.findViewById(R.id.order_list_taxes);
tvTotal = (TextView) orderDialogLayout.findViewById(R.id.order_list_grand_total);
Button bclose = (Button) orderDialogLayout.findViewById(R.id.close);
Button bPlaceOrder = (Button) orderDialogLayout.findViewById(R.id.my_order_placeorder);
bclose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
orderDialog.dismiss();
System.out.println(" click on closowse");
}
});
bPlaceOrder.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Place order click");
palceMyOrdertoServer();
new SendOrderFromTable().execute();
System.out.println("place order to server is called");
String msg = "Your Order is Successfully placed to Kitcken";
Message msgObject = new Message();
msgObject.what = 1;
msgObject.obj = msg;
addMenuItemHandler.sendMessage(msgObject);
orderDialog.dismiss();
}
});
}
and at last i am going to post showOrderListDialog(); block
public void showOrderListDialog() {
builder.setView(orderDialogLayout);
orderDialog = builder.create();
orderDialog.show();
}
I know i have posted too many codes but its conveniences for those who want to help me . I have a very simple problem why my
orderDialog.dismiss();
is not working for me.? Thanks in advance to all .
Finally i solve my own issue . "Self help is best help ;;".
It was issue of calling method in setOnClickListener.
I just call it,
android:clickable="true"
android:onClick="clickHandler"
if (v.getId() == R.id.myOrder) {
System.out.println("Click my Order");
System.out.println("OrderListAdapter.totalCount ="
+ OrderListAdapter.totalCount);
// select COUNT(*) from CDs;
int jcount = 0;
jcount = countjournals();
System.out.println("jcount = " + jcount);
// Count implementation at my Order
if (jcount < 1) {
alertShow();
} else {
intiliazeOrderListDialog();
showOrderListDialog();
}
// startActivity(new Intent(RestaurantHome.this,
// MyOrderList.class));
}
Need some advice again.
I am 99% done with this module I'm working on, although I'm stuck at the last hurdle. I'm dynamically publishing a button on the screen at runtime. This button will take it to a new activity view when pressed. I got that working perfectly.
However, I have another button which randomly changes the view so it effectively needs to reset itself, if that makes sense. What's happening is each time the button is clicked (the dynamic one) it then adds another button to the stack. Effectively I have buttons each time I click running down the screen. Is my logic wrong or is there a way to check and prevent the button to show each time? i.e. Just once...Below is the code.
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
Button myButton = new Button(this);
myButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(myButton);
final Button myButton1 = myButton;
myButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
break;
}
}
EDIT: How about this? Add a new class field member (a class variable, not a method's local variable) that indicates whether the button was actually added in the layout.
private boolean buttonShown = false; /* Here changed */
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
if (buttonShown == false) { /* Here changed */
Button myButton = new Button(this);
myButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(myButton);
final Button myButton1 = myButton;
myButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
buttonShown = true; /* Here changed */
} /* Here changed */
break;
}
}
Edited again: Instead of local variable myButton, I used class field member pressMeButton.
private Button pressMeButton;
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
if (pressMeButton == null) {
pressMeButton = new Button(this);
pressMeButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(pressMeButton);
}
/* If the pressMeButton is already in the layout, all you need to do is just changing the onClickListener. */
pressMeButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
break;
}
}
Your code is fine but the way it is it will always add a button to the screen. Whats the desired behavior your looking for? If its a conditional thing than you need to account for that in the onclick call.
EDIT:
So what you need to do then is to create some kind of flag or id for the button and set it as the button's view.tag like this:
Button b = new Button(context);
b.setTag(flagTag);
Then when you want to check if the button exists you check it like:
if((LinearLayout) findViewById(R.id.nextPageContainer))
.findViewById(tagFlag)==null){
Button b = new Button(context);
b.setTag(flagTag);
}else{
//do nothing or something :p
}
Sorry if the title was a bit vague.
I'm developing an app on Freelancer and I almost have it finished except for a complaint from the customer after some testing.
I use a PopupWindow in place of a dialog to edit contextual settings, if that makes any sense. I don't want to be too specific and risk giving the app concept away, which I'm sure the customer wouldn't be too pleased about.
The PopupWindow is given a Content View of a layout inflated from XML. In that layout are several EditText widgets. The issue is that those EditTexts will not trigger the default contextual dialog on long press that presents options for text/IME selection, and cut/copy/paste.
I saw a similar question trying to get the TouchTrigger or something and it not working without setBackgroundDrawable(), which I've tried with a simple new ColorDrawable(). It still doesn't work.
Is there any easy way to trigger the system-default long-press dialog in an OnLongPressListener, or will I have to move Heaven and Earth to implement it myself? Because if that's the case, I'll just write a Fragment for it and swap it out in a transaction. I know that'll work.
The relevant code:
Inside the initiating fragment:
RulesDialog dialog;
PopupWindow window;
public void showAddRuleDialog(){
dialog = new RulesDialog();
View view = getView();
window = new PopupWindow(dialog.initViews(this, null), view.getWidth(), view.getHeight(), true);
window.setBackgroundDrawable(new ColorDrawable());
dialog.setRulesDialogListener(new rulesDialogListener(){
#Override
public void onSave(ViewHolder holder) {
addRule(holder);
window.dismiss();
}
#Override
public void onCancel() {
window.dismiss();
}});
int[] location = {0,0};
view.getLocationOnScreen(location);
window.showAtLocation(view, 0, location[0], location[1]);
In RulesDialog:
public class ViewHolder{
public ViewHolder(View dialogView){
name = (TextView) dialogView.findViewById(R.id.name);
response = (TextView) dialogView.findViewById(R.id.response);
senders = (TextView) dialogView.findViewById(R.id.senders);
sendersAdd = (Button) dialogView.findViewById(R.id.sendersAdd);
sendersEdit = (Button) dialogView.findViewById(R.id.sendersEdit);
timeFrom = (TextView) dialogView.findViewById(R.id.from);
timeFromEdit = (Button) dialogView.findViewById(R.id.timeBeforeEdit);
timeTo = (TextView) dialogView.findViewById(R.id.to);
timeToEdit = (Button) dialogView.findViewById(R.id.timeAfterEdit);
keywords = (TextView) dialogView.findViewById(R.id.keywords);
matchCase = (CheckBox) dialogView.findViewById(R.id.matchCase);
matchAlone = (CheckBox) dialogView.findViewById(R.id.matchAlone);
matchPlural = (CheckBox) dialogView.findViewById(R.id.matchPlural);
cancel = (Button) dialogView.findViewById(R.id.cancel);
save = (Button) dialogView.findViewById(R.id.save);
}
TextView name;
TextView response;
TextView senders;
Button sendersAdd;
Button sendersEdit;
TextView timeFrom;
Button timeFromEdit;
TextView timeTo;
Button timeToEdit;
TextView keywords;
CheckBox matchCase;
CheckBox matchAlone;
CheckBox matchPlural;
Button cancel;
Button save;
}
Activity activity;
ViewHolder holder;
Fragment fragment;
public View initViews(Fragment mFragment, Rule rule){
fragment = mFragment;
activity = fragment.getActivity();
View dialogView = LayoutInflater.from(activity).inflate(R.layout.rules_dialog, null);
holder = new ViewHolder(dialogView);
final TextView senders = holder.senders;
holder.sendersAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showContacts();
}});
holder.sendersEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
editSenders(senders);
}
});
final TextView timeFrom = holder.timeFrom;
holder.timeFromEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showTimePickerDialog(timeFrom);
}
});
final TextView timeTo = holder.timeTo;
holder.timeToEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showTimePickerDialog(timeTo);
}
});
holder.cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mListener.onCancel();
}});
holder.save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mListener.onSave(holder);
}});
if(rule == null)
rule = new Rule();
holder.name.setText(rule.name);
holder.response.setText(rule.response);
holder.senders.setText(rule.senders.toString());
holder.senders.setTag(rule.senders);
holder.keywords.setText(rule.keywords);
holder.matchCase.setChecked(rule.matchCase);
holder.matchAlone.setChecked(rule.matchAlone);
holder.matchPlural.setChecked(rule.matchPlural);
holder.timeFrom.setTag(rule.timeFrom);
holder.timeFrom.setText(Rules.formatTime(rule.timeFrom));
holder.timeTo.setTag(rule.timeTo);
holder.timeTo.setText(Rules.formatTime(rule.timeTo));
return dialogView;
}
So I tried rewriting RulesDialog as a fragment, and it didn't work out too well. Had issues with making Fragment Transactions work right when called from the Fragments they're operating on.
(I know this isn't the point to fragments. I'm not really aiming to write a completely modular app right now. I just want to come out with a product the customer will be happy with.)
I ended up rewriting RulesDialog as an Activity instead, and using startActivityForResult() from the calling fragment. Then passing the edited data back with setResult(). It all works nicely in concert.