How to create a dialog outside MainActivity in android - java

I want to insert an alert dialog into my android app.
It's fine when I follow the tutorial to add it in a simple project, which only has a MainActivity.java, activity_main.xml and a layout xml.
However, when I want to insert the code into my project, I get some questions.
My code is:
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Are you sure want to QUIT ?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
pmaControllerManager.OnExit();
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
})
.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.show();
There is a warning symbol in the this in the first line.
How could I fix it?
p.s. below is the function where I call showDialog(I call it in buttons[5]):
private void setbutton()
{
buttons[0]=(ImageButton)menu.findViewById(R.id.button0);
buttons[1]=(ImageButton)menu.findViewById(R.id.button1);
buttons[2]=(ImageButton)menu.findViewById(R.id.button2);
buttons[3]=(ImageButton)menu.findViewById(R.id.button3);
buttons[4]=(ImageButton)menu.findViewById(R.id.button4);
buttons[5]=(ImageButton)menu.findViewById(R.id.button5);
buttons[1].setBackgroundResource(R.drawable.screen);
buttons[2].setBackgroundResource(R.drawable.sketch);
buttons[3].setBackgroundResource(R.drawable.importdraw);
buttons[4].setBackgroundResource(R.drawable.setting);
buttons[5].setBackgroundResource(R.drawable.out);
center.setBackgroundResource(R.drawable.noticeicon_using);
/*center.setOnClickListener(new ImageButton.OnClickListener(){
#Override
public void onClick(View v) {
if(click)
{
closemenu();
//mode=false;
}
else
{
openmenu();
//mode=true;
}
click=!click;
}
});*/
center.setOnTouchListener(new View.OnTouchListener() {
boolean isMove=false;
int touchy,touchx,y;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action=motionEvent.getAction();
if(action==MotionEvent.ACTION_DOWN)
{
y=params.y;
//Log.i("y:",String.valueOf(y));
touchy=(int)motionEvent.getRawY();
touchx=(int)motionEvent.getRawX();
}
else if(action==MotionEvent.ACTION_MOVE)
{
if(Math.abs(motionEvent.getRawX()-touchx)<30)
{
isMove=true;
params.gravity=Gravity.RIGHT;
params.y=y+(int)motionEvent.getRawY()-touchy;
wm.updateViewLayout(center,params);
wm.updateViewLayout(menu,params);
}
}
else if(action==MotionEvent.ACTION_UP)
{
if(!isMove)
{
if(click)
{
closemenu();
//mode=false;
}
else
{
openmenu();
//mode=true;
}
click=!click;
}
else
isMove=false;
}
return true;
}
});
buttons[1].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[1].setBackgroundResource(R.drawable.screen_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[1].setBackgroundResource(R.drawable.screen);
pmaControllerManager.newTask("screen");
}
return true;
}
});
buttons[2].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[2].setBackgroundResource(R.drawable.sketch_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[2].setBackgroundResource(R.drawable.sketch);
pmaControllerManager.newTask("sketch");
}
return true;
}
});
buttons[3].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[3].setBackgroundResource(R.drawable.importdraw_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[3].setBackgroundResource(R.drawable.importdraw);
}
return true;
}
});
buttons[4].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[4].setBackgroundResource(R.drawable.setting_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[4].setBackgroundResource(R.drawable.setting);
pmaControllerManager.Setting();
}
return true;
}
});
buttons[5].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[5].setBackgroundResource(R.drawable.exit_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[5].setBackgroundResource(R.drawable.out);
shoaDialog(menuwindow.this);
pmaControllerManager.OnExit();
}
return true;
}
});
}

Pass Context instead of this because this is a reference to the current object. It means if you call it for example from lambda this will be a reference of object which is extended from anonymous class.
so you can make method like
public void showDialog(Context context) {
AlertDialog alartDialog = AlertDialog.Builder(context).
...
.show();
}
and then call it like
showDialog(MainActivity.this); //for activity
showDialog(MainFragment.this.getActivity()); //for fragment
By the way better to make something like Util class for it:
class DialogUtil {
public static void showDialog(Context context) {
AlertDialog alartDialog = AlertDialog.Builder(context).
...
.show();
}
}
Then call it like
DialogUtil.showDialog(MainActivity.this); //for activity
DialogUtil.showDialog(MainFragment.this.getActivity()); //for fragment
UPDATE
Instead of calling it like:
shoaDialog(menuwindow.this);
You can pass Context as I described above or you can get it from View:
buttons[5].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//some code here
showDialog(v.getContext());
return true;
}
});

replace this to MainActivity.this like :
android.app.AlertDialog alartDialog = new
android.app.AlertDialog.Builder(MainActivity.this)

The AltertDialog requires a context and you are passing it the activity. Try using
new android.app.AlertDialog.Builder(this.getApplicationContext())
instead.

Replace this with MainActivity.this or getApplicationContext()
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(MainActivity.this)
If you are using dialog look below :
For Activity : ActivityName.this
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(MainActivity.this)
For Fragment : getActivity()
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(getActivity())
For Adapter : Context context;
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(context)
Also, Look into this Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Related

I want to display some text onDoubleClick event how to do so ? i have attached my sourcecode Along

I want to apply a doubleClick event on a text field which displays some text on double click event but it keeps giving me errors is there any method to just simply doing this
TextView tv;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.mytext);
tv.setOnTouchListener(new OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
tv.setText("DoubleTouch");
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
tv.setText("Double Touch ");
return true;
}
}
);
}
You should initialize the Gesture Detector like this
GestureDetector gd = new GestureDetector(this, new GestureDetector.OnGestureListener() {
#Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
});
Then set on double click listener like this
gd.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
return false;
}
});
Finally you apply the listener to your View like this
tv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
gd.onTouchEvent(event);
return false;
}
});
Refer Android docs for more info Detect Common gestures

set OnFocusChangeListener for more editTexts in Fragment

I want to set automatic scroll for each EditText(VerifiedEditText in my case) I have.
I did it this way but I don't think it is the way it should be done (looks too complicated, messy and too long), would you please recommend me making it anyway simpler? I am still learning by myself, so an explanation to attached code would be really appreciated. Thank you
#Override
public void onFocusScroll() {
final ScrollView mScrollView;
mScrollView = (ScrollView) rootView.findViewById(R.id.register_scroll);
final VerifiedEditText editText0 = (VerifiedEditText) rootView.findViewById(R.id.register_ticket);
final VerifiedEditText editText1 = (VerifiedEditText) rootView.findViewById(R.id.register_sektor);
final VerifiedEditText editText2 = (VerifiedEditText) rootView.findViewById(R.id.register_row);
final VerifiedEditText editText3 = (VerifiedEditText) rootView.findViewById(R.id.register_seat);
editText0.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mScrollView.post(new Runnable() {
public void run() {
mScrollView.smoothScrollTo(0, mScrollView.getTop());
}
});
}
}
});
editText1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mScrollView.post(new Runnable() {
#Override
public void run() {
mScrollView.smoothScrollTo(0, mScrollView.getBottom());
}
});
}
}
});
editText2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mScrollView.post(new Runnable() {
#Override
public void run() {
mScrollView.smoothScrollTo(0, mScrollView.getBottom());
}
});
}
}
});
editText3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mScrollView.post(new Runnable() {
#Override
public void run() {
mScrollView.smoothScrollTo(0, mScrollView.getBottom());
}
});
}
}
});
}
implement class by `View.OnFocusChangeListener`
and set Focus Listener to the current instanace of class because treat as View.OnFocusChangeListener instnace
and Override onFocusChange() medthod
v.getTop() return top position of current focused view
editText0.setOnFocusChangeListener(this);
editText1.setOnFocusChangeListener(this);
editText2.setOnFocusChangeListener(this);
editText3.setOnFocusChangeListener(this);
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mScrollView.post(new Runnable() {
public void run() {
mScrollView.smoothScrollTo(0, v.getTop());
}
});
}
}
}

WebView Go Back Button inside Fragment

Inside a fragment, I'm using WebView. I simply query 2 options when Back Button Clicked
First if; url.equals("www.google.com") [which works perfectly]
Second if; !url.equals("www.google.com") [doesn't work]
I worked in debug mode, but my second if doesn't work, even though url is different than "google.com" and closes the app!
Fragment.Java
#Override
public void onResume() {
super.onResume();
if (getView() == null) {
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if(url.equals("https://www.google.com")){
//normal geri
final AlertDialog.Builder builder_question1 = new AlertDialog.Builder(getContext());
builder_question1.setTitle("Are you sure to close the app?");
builder_question1.setCancelable(true);
//POSITIVE BUTTON
builder_question1.setPositiveButton("yes",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
System.exit(0);
}
});
//NEGATIVE BUTTON
builder_question1.setNegativeButton("no",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//do something...
//and dismiss
dialogInterface.dismiss();
}
});
builder_question1.create().show();
}
if(!url.equals("https://www.google.com")){
if(webView.canGoBack()){
webView.goBack();
}
}
}
return true;
}
});
}
WebViewClient
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Toast.makeText(getContext(), ""+url, Toast.LENGTH_SHORT).show();
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
// Toast.makeText(getContext(), "page loaded", Toast.LENGTH_SHORT).show();
super.onPageFinished(view, url);
}
});
webView.loadUrl(url);
Apply Back button in activity containing fragment
it's one of an issue, the application gets crash for a second time because of wrong context type in dialog builder when you try to display the dialog.
Change the AlertDialog context from getContext() to getActivity(); and System.exit(0); with getActivity().finish();
final AlertDialog.Builder builder_question1 = new AlertDialog.Builder(getActivity());
builder_question1.setTitle("Are you sure to close the app?");
builder_question1.setCancelable(true);
//POSITIVE BUTTON
builder_question1.setPositiveButton("yes",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().finish();
}
});
if(!url.equals("https://www.google.com")){
if(webView.canGoBack()){
webView.goBack();
return false;
}
}
Maybe this helps you
if(url.equals("https://www.google.com")){
//normal geri
} else {
if(webView.canGoBack()){
webView.goBack();
}
}

Swipe gesture not recognized

For my Buttons onClickListener I have the following code:
on_enter_button.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
enter(words, linearLayout, llp, view);
}
});
Instead of pressing enter Button, I simply want to Swipe the screen in any direction and run the same method: enter(words, linearLayout, llp, view);
Currently I think my program does not recognize Swipe gestures at all. I assume it's because I placed enter(words, linearLayout, llp, view); incorrectly. Also, I put all the Gesture recognition code inside the onCreate(). Is that the correct way to program the code?
Can someone please help?
EDITED CODE:
public class Game extends Activity{
public void enter(String[] w, LinearLayout ll, LinearLayout.LayoutParams params, View v){
... //some code
... //some code
... //some code
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return myGestureDetector.onTouchEvent(event);
//error myGestureDetector not recognized since it's created in onCreate so it does not exist here
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
SimpleOnGestureListener mySimpleGestureListener = new SimpleOnGestureListener()
{
#Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
#Override
//swipe does not work!
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return super.onSingleTapConfirmed(e);
}
private boolean permissibleYVelocity(float velocityY)
{
if ((velocityY < -200) || (velocityY > 200))
{
return false;
}
else
{
return true;
}
}
};
final GestureDetector myGestureDetector = new GestureDetector(getApplicationContext(), mySimpleGestureListener);
//button listener works
on_enter_button.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
enter(words, linearLayout, llp, view);
}
});
}
}
You need to override View.onTouchEvent().
#Override
public boolean onTouchEvent(MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
Call your method in SimpleOnGestureListener.onFling():
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return true;
}
EDIT:
Setup your GestureDectector in onCreate() as well:
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return super.onSingleTapConfirmed(e);
}
private boolean permissibleYVelocity(float velocityY)
{
if ((velocityY < -200) || (velocityY > 200))
{
return false;
}
else
{
return true;
}
}
});

Creating DialogFragment with EditText

I'm new to android, started it about a month ago, and now I'm trying to make a "Shopping List" app for the sake of practice. In this app I have a ListView, where user can insert items via EditText above that ListView. When user longClick on item, ContextMenu with "Edit", "Delete" and "Mark" fields appears. I have already made "Delete" button work, but I still have problems with "Edit" function. To make this function work I created DialogFragment class, so when user presses the "Edit" button, this DialogFragment appears. This DF has EditText field, where we enter data we want to change. Here is DialogFragment class code:
public class AlertEdit extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
bd.setView(inflater.inflate(R.layout.alert, null))
.setTitle("Edit")
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doNegativeClick();
}
});
return bd.create();
}
as you can see, we have positive button here, which calls doPositiveClick method from MyActivity, which appears to be the main activity.
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
So, here is the MyActivity class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
lw = (ListView) findViewById(R.id.listView);
edtxt = (EditText) findViewById(R.id.editText);
alertEd = (EditText) findViewById(R.id.alertEdit);
goods = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, goods);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
}
});
registerForContextMenu(lw);
edtxt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
goods.add(0, edtxt.getText().toString());
adapter.notifyDataSetChanged();
edtxt.setText("");
return true;
}
}
return false;
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, v, info);
getMenuInflater().inflate(R.menu.actions, menu);
}
public boolean onContextItemSelected(MenuItem item) {
position = (int) info.id;
switch (item.getItemId()) {
case R.id.cnt_mnu_delete:
goods.remove(position);
adapter.notifyDataSetChanged();
return true;
case R.id.cnt_mnu_edit:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doPositiveClick()
{
}
public void doNegativeClick()
{
}
public void showDialog()
{
DialogFragment frag = new AlertEdit();
frag.show(getFragmentManager(), "edit");
}
}
My problem is that I have no idea how to create that Edit function. I tryied to use AdapterContextMenuInfo, but it works only in onContextItemSelected method, because it requires and Item to work with. Hope you help me and sorry for the possible lack of information, ask me any additional questions please.
P.S. I'm trying to make this dialog for almost two weeks already and I'm really frustrated because of that.
I'm using this method - it's simple and you may adapt it to your needs:
First of all make an interface to handle your result, for example:
public interface OnDialogResultListener {
public void onDialogResult(String result);
}
Then use your dialog with additional view, like this:
public void showDialogAndGetResult(final int title, final String message, final String initialText, final OnDialogResultListener listener) {
// additional View - use appropriate View to your needs:
final EditText editText = new EditText(this);
editText.setText(initialText);
new AlertDialog.Builder(MainActivity.this)//
.setTitle(title)//
.setMessage(message)//
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onDialogResult(editText.getText().toString());
}
}
})//
.setNegativeButton(android.R.string.cancel, null)//
.setView(editText)//
.show();
}
At last implement this interface in your activity:
public class YourActivity Extends Activity implements OnDialogResultListener{
...
#Override
public void onDialogResult(String result) {
//do what you need
}
...
}
Edit:
You may replace EditText by any View, including Layouts.
Still you may use the same scheme to return result from your DialogFragment descendant - just pass OnDialogResultListener in constructor or initializing method. I would say AlertDialog is more lightweight and DialogFragment allows more control and you may use both according to your needs.

Categories

Resources