How to Add multiple choice checkboxes in alert Dialog in Android? - java

I have created menu "Sync" in android app. when we click on "Sync" alert open a 4 checkboxes layout. what I want is to have them in function like when I click on 15 minutes then other option unclicked automatically.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_settings:
alertDialog = new AlertDialog.Builder(HomePage.this).create(); //Read Update
LayoutInflater adbInflater = this.getLayoutInflater();
View checkboxLayout = adbInflater.inflate(R.layout.sync_layout, null);
defaultchkbox = (CheckBox)checkboxLayout.findViewById(R.id.defaultchkbox);
after15mint = (CheckBox)checkboxLayout.findViewById(R.id.after15mint);
after30mint = (CheckBox)checkboxLayout.findViewById(R.id.after30mint);
after45mint = (CheckBox)checkboxLayout.findViewById(R.id.after45mint);
alertDialog.setView(checkboxLayout);
alertDialog.setTitle("Synchronization");
alertDialog.setMessage("Choose");
alertDialog.setButton(Dialog.BUTTON_POSITIVE,"Save changes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
boolean checkBoxResult = false;
if(after15mint.isChecked())
{
Toast.makeText(getApplicationContext(), "15 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else if(after30mint.isChecked())
{
Toast.makeText(getApplicationContext(), "30 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else if(after45mint.isChecked())
{
Toast.makeText(getApplicationContext(), "45 Minute checked", Toast.LENGTH_LONG).show();
checkBoxResult = true;
}
else{
Toast.makeText(getApplicationContext(), "Default", Toast.LENGTH_LONG).show();
}
}
});
alertDialog.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
But I am little bit confused over working of check boxes in alert. Suggestions will be great help. Thank you. :)

It looks like you need to work with Radio Buttons which are nested within a RadioGroup. It will then only allow you to select one option at a time.
For more information on RadioGroup look at:
http://developer.android.com/reference/android/widget/RadioGroup.html
For more information on creating Radio Buttons look at:
http://developer.android.com/reference/android/widget/RadioButton.html
in particular to your code you will have to define RadioButtons within a RadioGroup in your R.layout.sync_layout like for example
<RadioGroup
android:id="#+id/syncGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/defualt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Default"
android:checked="true" />
<RadioButton
android:id="#+id/minute15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "15 Minute" />
<RadioButton
android:id="#+id/minute30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "30 Minute" />
<RadioButton
android:id="#+id/minute45"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "45 Minute" />
</RadioGroup>

See this link.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color);
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}

Related

Listening For Touch In Padding Area Between Elements of An AlertDialog

I have onTouchListeners for the (custom) title area and for the message area of my AlertDialog.
I'm trying to have my dialog set up in such a way that the user can mindlessly tap in the top right 1/4th of the AlertDialog to toggle the whether background music plays or not since just having the speaker as the tappable area would result in too small of a hit box/area.
My problem is: the area in between the message and title marked in red isn't handling ontouchlistener events
Most people would suggest creating a custom dialog, but the thing is I really like the way this dialog looks (it has a very stock material design aesthetic) and already jumped through a lot of hoops to get it to look exactly the way I like (drawing leaderboard over an invisible neutral button, custom title area). I don't want to make a custom dialog unless I can make it look absolutely identical to what I have now (so hard to mimic the look of stock material dialogs, trust me i've tried and did a lot of research/wasted a lot of time trying that).
I'm assuming the on touch events for the custom title area and message area don't encompass or account for the margins or padding in between.
Pardon the disgusting code!! I'm just trying to hack everything together and tidy it up later.
Thanks in advance!
The linear layout for my custom title area of the alertdialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0px"
android:paddingTop="0px"
android:paddingLeft="0px"
android:paddingRight="0px"
android:paddingBottom="0px"
android:orientation="horizontal"
android:id="#+id/st"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="24dp"
android:paddingTop="20dp"
android:paddingRight="5dp"
android:src="#drawable/ic_pause"/>
<TextView
android:id="#+id/leaderboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#800080"
android:textSize="22sp"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
android:layout_gravity="center"
android:paddingTop="18dp"
android:layout_weight="1"
android:text="Paused"
/>
<ImageView
android:id="#+id/soundtoggle"
style="?android:attr/panelTextAppearance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="24dp"
android:paddingTop="20dp"
android:paddingRight="?android:dialogPreferredPadding"
android:gravity="right"/>
</LinearLayout>
My android code
AlertDialog.Builder ad = new AlertDialog.Builder(new ContextThemeWrapper(AndroidLauncher.this, android.R.style.Theme_Material_Light_Dialog))
.setMessage(msg)
.setCustomTitle(myLayout)
.setCancelable(false)
.setNegativeButton("End Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pauseInterface.end();
dialog.cancel();
}
})
.setNeutralButton(" ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//startSignInIntent();
showLeaderboard();
dialog.cancel();
}
})
.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pauseInterface.resume();
dialog.cancel();
}
});
alertDialog = ad.create();
int titleId = getResources().getIdentifier("alertTitle", "id", "android");
if (titleId > 0) {
TextView dialogTitle = (TextView) alertDialog.findViewById(titleId);
}
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
Drawable drawable = getResources().getDrawable(R.drawable.ic_leaderboard);
drawable.setBounds((int) 0,
0, (int) (drawable.getIntrinsicWidth() * 1),
drawable.getIntrinsicHeight());
button.setCompoundDrawables(drawable, null, null, null);
}
});
alertDialog.show();
final ImageView soundToggle = (ImageView) alertDialog.findViewById(R.id.soundtoggle);
if (tetrisgame.getMusicState()) {
if (tetrisgame.getMusicState()) {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_on, getApplicationContext().getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, getApplicationContext().getTheme()));
}
TextView tv = (TextView) alertDialog.findViewById(android.R.id.message);
tv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN && (m.getX() >= (v.getRight() - (v.getWidth() / 4)))) {
Log.println(Log.ERROR, "Ken", "Popular Pothead");
if (tetrisgame.toggleMusic()) {
String uri = "#drawable/music_on"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
soundToggle.setImageDrawable(res);
// soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, alertDialog.findViewById(android.R.id.message).getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, null));
}
}
return true;
}
});
final LinearLayout as = (LinearLayout) alertDialog.findViewById(R.id.st);
as.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN) {
Log.println(Log.ERROR, "Ken", "Tweed");
if (tetrisgame.toggleMusic()) {
String uri = "#drawable/music_on"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
soundToggle.setImageDrawable(res);
// soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, alertDialog.findViewById(android.R.id.message).getTheme()));
} else {
soundToggle.setImageDrawable(getResources().getDrawable(R.drawable.music_off, null));
}
}
return true;
}
});

Issue with Start Button on Android Calculator

I am working on an Android calculator app not using any of the built in timer based classes in Android, but instead using Handlers and Threads to update the UI. I'm not sure if there is a problem with my logic or not, but for whatever reason when I set a time and hit the Start button, nothing happens on the screen at all. The targeted TextView does not decrease as it should. Again, I may have made a simple errors (or a few), but I am posting my java and xml files for you all to look at. Thanks in advance for any responses.
TimerActivity.java
package com.example.stins.intentsandtimer;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.os.Vibrator;
public class TimerActivity extends AppCompatActivity implements View.OnClickListener {
TextView hours, minutes, seconds;
Button numberPicker;
private int hrs, min, sec;
private boolean start;
Handler timerHandler = new Handler(){
/**
* Handler for the timer class. It receives the onStart runnable to allow the textviews
* to be updated. It checks to see if all textviews are empty and only updates them if
* they follow the conditions of a traditional timer. Including moving from 1 hour to 59 minutes.
* The handler also sends the Vibrator function once the timer is complete.
* #param msg
*/
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
int zeroCheck = Integer.parseInt(txtSeconds.getText().toString());
if (zeroCheck > 0) {
sec -= 1;
txtSeconds.setText(sec + "");
} else if (min > 0 && sec == 0) {
min -= 1;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else if (hrs > 0 && min == 0 && sec == 0) {
hrs -= 1;
txtHours.setText(hrs + "");
min = 59;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
this.setTitle("Timer");
Button btnStart = (Button) findViewById(R.id.start_button);
Button btnStop = (Button) findViewById(R.id.stop_button);
Button btnReset = (Button) findViewById(R.id.reset_button);
hours = (TextView) findViewById(R.id.textview_hours);
numberPicker = (Button) findViewById(R.id.btn_set_hours);
numberPicker.setOnClickListener(this);
minutes = (TextView) findViewById(R.id.textview_minutes);
numberPicker = (Button) findViewById(R.id.btn_set_minutes);
numberPicker.setOnClickListener(this);
seconds = (TextView) findViewById(R.id.textview_seconds);
numberPicker = (Button) findViewById(R.id.btn_set_seconds);
numberPicker.setOnClickListener(this);
btnReset.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
sec = 0;
min = 0;
hrs = 0;
txtSeconds.setText(sec+"");
txtMinutes.setText(min+"");
txtHours.setText(hrs+"");
}
}
);
btnStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = true;
onStart();
}
}
);
btnStop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = false;
}
}
);
}
protected void onStart(){
super.onStart();
final Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
while (sec > 0 || min > 0 || hrs > 0) {
if(start) {
try {
Thread.sleep(1000);
timerHandler.sendMessage(timerHandler.obtainMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else{
}
}
}
});
myThread.start();
}
public void onClick (View v){
switch (v.getId()) {
case R.id.btn_set_hours:
hourPickerDialog();
break;
case R.id.btn_set_minutes:
minutePickerDialog();
break;
case R.id.btn_set_seconds:
secondPickerDialog();
break;
default:
break;
}
}
private void hourPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(99);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
hours.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Hours");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void minutePickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
minutes.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Minutes");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void secondPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
seconds.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Seconds");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
activity_timer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/textview_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="#+id/btn_set_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hours"/>
<Button
android:id="#+id/btn_set_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Minutes"/>
<Button
android:id="#+id/btn_set_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seconds"/>
</LinearLayout>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_start"
style="#style/MyButton"
/>
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_stop"
style="#style/MyButton"/>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_reset"
style="#style/MyButton"/>
</LinearLayout>
There's several things going on in your code. I won't try to address them all but just some to get your code doing about what it should. I've copied & tried your code & it actually changes the display for me. I skipped your time picker dialogs & just set sec=20 to start. If you're not getting any changing display, is the display being set initially from the time pickers?
Anyway, 1st let's talk about debugging. One way to do this is to put Log statements in your code. Start by putting this at the top of the file
private final static String TAG = "TimerActivity";
Then in the code have things like this:
// put this in the start button click listener
Log.d(TAG, "Start clicked");
// or this in handleMessage
Log.d(TAG, "handleMessage(), seconds = " + sec);
Having these Log message can help you know what your program has done & what it hasn't, plus show you some variable values. You could also use the debugger which I won't get into now.
Now for your code. onStart() is a lifecycle method. You should not call it yourself. Rename your method (maybe something like onStartButton()). As you have it now, you have 2 instances of your thread running and your counter goes down twice in each second.
In handleMessage(), you have variables (hrs, min, sec) that you use to track the time but you also have zeroCheck that you read from the text on the display. The better thing to do would be use the variables you're already keeping anyway (if(sec > 0) { sec -= 1;...). I didn't verify your logic in the rest of these conditions. Once the display is updating, I'll leave that for you.
Lastly, txtSeconds.setText(sec + ""); is not a good way to use setText() (it's probably OK for Log messages but it's better to get accustomed to using text in other ways). There is more than 1 good way to display text but for this instance, you need special formatting. That is you want your display to show a leading 0 for each number "00:09:07" not "0:9:7". You can get that with
txtSeconds.setText(String.format("%02d", sec));
This way always gives a 2 digit display, from 0 to 59. Other useful formatters are "%08x" for 32 bit hexadecimal or "%.2f" which limits display to 2 places past the decimal place like for showing dollars and cents.
So, none of these will fix the problem in your post but they will get your final code closer to what it needs to be. As I said, your code updates the display as it is for me (not using the time pickers). You can start by setting sec to a fixed number then hit the "Start" button to see what happens. If there are problems in your time pickers, you can use Log messages to track down the bugs & fix them.
EDIT:
So what's happening with your timer not starting is that, while you change the display in your number picker, you don't set the underlying variables (sec etc.) Define some variables to use as temp storage (temp_sec etc.) then set this in onValueChange(),
temp_sec = newVal;
Now in your positiveButton onClick(), you'll have
sec = temp_sec;

Change the behaviour of "imeOptions" (Android)

This is my problem right now, guys.
I have the next TextView and EditText
activity_profile.xml
<TextView
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/done"
android:id="#+id/done_profile_btn"
android:textColor="#color/white"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:id="#+id/input_profile_swift"
android:hint="#string/swift"
android:inputType="textCapCharacters"
android:textColor="#color/colorPrimaryDark"
android:layout_marginBottom="22dp"
android:maxLines="1"
android:imeOptions="actionDone"/>
And I would like to change the action that press the 'Done' button on the keyboard does for the EditText in order to do the same as the TextView, which does the next:
ProfileActivity.java
done_btn = (TextView) findViewById(R.id.done_profile_btn);
swift = (EditText)findViewById(R.id.input_profile_swift);
done_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//saveChanges();
//finish();
Toast.makeText(getApplicationContext(), "Your changes have been saved", Toast.LENGTH_SHORT).show();
}
});
...
So... I want that both (press 'Done' on my keyboard and press the TextView) do the same.
Any idea of how to do that? Thank you very much.
You can use this one also (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:
swift.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
//saveChanges();
//finish();
Toast.makeText(getApplicationContext(), "Your changes have been saved", Toast.LENGTH_SHORT).show();
}
return false;
}
});
Hope it will help !
try this
EditText swift = (EditText)findViewById(R.id.input_profile_swift);
swift.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Toast.makeText(getApplicationContext(), "Your changes have been saved", Toast.LENGTH_SHORT).show();
}
}
});
You have to implements OnEditorActionListener interface and set it to your EditText. using setOnEditorActionListener(OnEditorActionListener implimentation.)
Use TextView.OnEditorActionListener.
#Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
KeyboardHelper.hideSoftKeyboard(getActivity());
doSomeWoorrkThatYouNeed();
return true;
}
You should add this android:clickable="true" to your xml for the TextView.
Also you could set an EditorActionListener using setOnEditorActionListener on your EditText in similar way that you did with setOnClickListener for your TextView.

Choose where to save a file in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have an object("jsonized" to a string) and I want to save it in a file.
Also, I want that a dialogbox shows up allowing the user to pick up the folder where the file will be saved.
(I was writing this question when, suddenly, the solution hit me. Just sharing my solution to get feedback of better ways to do this)
When the "Save File" button is clicked, it launches "selectFolder()" function
Activity.java
public void selectFolder(){
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Chain together various setter methods to set the dialog characteristics
builder.setTitle("Choose folder to save profile");
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_selectfolder, null);
ListView lvDirectories = (ListView) dialogView.findViewById(R.id.lvDirectories);
String path = Environment.getExternalStorageDirectory().toString();
((TextView) dialogView.findViewById(R.id.tvJamesBond)).setText(path);
final ArrayList<String> items = listFolders(path);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvDirectories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String dest = ((ListView) dialogView.findViewById(R.id.lvDirectories)).getItemAtPosition(i).toString().trim();
String path;
if(dest.compareTo("...")==0){
int lastSlash = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString().lastIndexOf("/");
path = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString().substring(0,lastSlash);
}
else{
path = ((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString() + "/" + dest;
}
items.clear();
items.addAll(listFolders(path));
((TextView) dialogView.findViewById(R.id.tvJamesBond)).setText(path);
adapter.notifyDataSetChanged();
}
});
lvDirectories.setAdapter(adapter);
adapter.notifyDataSetChanged();
builder.setView(dialogView);
// Add the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
saveProfile(((TextView) dialogView.findViewById(R.id.tvJamesBond)).getText().toString());
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast toast = Toast.makeText(getApplicationContext(), "Nothing saved", Toast.LENGTH_SHORT);
toast.show();
}
});
// Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
public ArrayList<String> listFolders(String path){
ArrayList<String> result = new ArrayList<String>();
File f = new File(path);
File[] files = f.listFiles();
Log.d("TEST PATH1", path);
Log.d("TEST PATH1", Environment.getExternalStorageDirectory().toString());
if(path.compareTo(Environment.getExternalStorageDirectory().toString())!=0){
result.add("...");
}
for (File inFile : files) {
if (inFile.isDirectory()) {
result.add(inFile.getName());
}
}
return result;
}
public void saveProfile(String folder){
String fileName = "default.txt";
try{
String ob = new Gson().toJson(((MyApplication)getApplication()).getProfile());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(folder+"/"+fileName));
outputStreamWriter.write(ob);
outputStreamWriter.close();
}
catch(IOException ex){
Log.e("SAVE_FILE", ex.toString());
}
Toast toast = Toast.makeText(getApplicationContext(), "Profile saved to file '"+fileName+"'", Toast.LENGTH_SHORT);
toast.show();
}
dialog_selectfolder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvDirectories"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
android:text="New Text"
android:id="#+id/tvJamesBond"
android:layout_gravity="center_horizontal" />
</LinearLayout>

search a website in android

I am in a development of an android that will search for a particular word in a website..for that I developed some code...but it is not complete...is anyone able to help..it will be a help for me...thank you so much for reading
public class MainActivity extends Activity {
EditText et = new EditText(this);
public void onClick(View v){
Editable searchText = et.getText();
Intent intent = new Intent(this, com.example.app.MainActivity.class);
intent.putExtra("searchQuery", searchText);
startActivity(intent);
}
}
Try it....
<EditText
android:id="#+id/edt_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:ellipsize="end"
android:hint="Enter Your Text"
android:imeOptions="actionGo"
android:singleLine="true"
android:textSize="14sp" />
EditText edt_search;
edt_search = (EditText) findViewById(R.id.edt_search_book);
edt_search.setImeOptions(EditorInfo.IME_ACTION_GO);
edt_search.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
// Log.i("KeyBoard" ,"Inside the Edit Text");
if (actionId == EditorInfo.IME_ACTION_GO) {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, edt_search.getText().toString()); // query contains
startActivity(intent); // search string
}
return false;
}
});

Categories