SeekBar in a DialogFragment - android

I am trying to read stuff from a SeekBar in Android that's within a DialogFragment. It keep crashing. The SeekBar alone comes up no problem, but whenever I try to override functions so I can use the SeekBar for something it keeps crashing. I've tried copying basically what I've seen other people post as working code (though not within a DialogFragment) but it doesn't work. Can someone tell me what's wrong here?
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
});`
It keeps crashing whenever I perform the action to open the DialogFragment. When I comment out the entire section it is fine. The problem is somehow overriding those functions, even when they're empty. When this entire section is commented the View comes up with SeekBars and TextViews.
I don't think this is important but here's the XML for the DialogFragment.
<?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:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Settings"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/seekBar1"
android:layout_marginTop="20dp"
android:text="NumShifts"
android:textAppearance="?android:attr/textAppearanceSmall" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:gravity="center"
android:layout_gravity="center"
android:max="15"
android:progress="6"
android:secondaryProgress="0"/>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:gravity="center"
android:layout_gravity="center"
android:max="9"
android:progress="3"
android:secondaryProgress="0"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/titleText"
android:layout_below="#+id/titleText"
android:layout_marginTop="18dp"
android:text="NumColumns"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
Here is the whole code from the class:
package com.example.[I have to hide this name];
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SettingsDialogueFragment extends DialogFragment
{
private int numColums;
private int numShifts;
private Context ctx;
private SeekBar numColumnsControl = null;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
ctx = getActivity();
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater= getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.settings_menu, null))
.setPositiveButton("DONE", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//done
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
LinearLayout settings = new LinearLayout(ctx);
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
Activity myActivity = getActivity();
if(myActivity == null)
{
Log.e("bill", "bill");
}
if(numColumnsControl == null)
{
Log.e("smith", "smith");
}
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
Log.e("asd", "asd");
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
Log.e("asdf", "asdf");
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
Log.e("asdfg", "asdfg");
// TODO Auto-generated method stub
}
});
return builder.create();
}
}

Based on your comment
'The error is a NullPointerException, which occurs on line 51 which is
the 2nd line in the fragment I gave you
("numColumnsControl.setOnSeekBarChangeListener(new
OnSeekBarChangeListener() ")'
Check if findViewById(R.id.Seekbar1) doesn't returns null. If it does, Make sure your dialog layout is inflated before requesting any view elements from the layout.
It is also possible something is going wrong with the R references (try project -> clean in eclipse) .
Edit I'm not sure if it works, but try to overide onViewCreated() and place your findViewById and setOnSeekBarChangeListener code here.
Edit in some way onViewCreated() is not called (Android DialogFragment onViewCreated not called). This makes the solution a little more difficult. You need to inflate the view first and perform an findViewById on the inflated view.
View menuView = inflater.inflate(R.layout.settings_menu);
numColumnsControl = (SeekBar) menuView.findViewById(R.id.seekBar1, null);
numColumnsControl.setOnSeekBarChangeListener ...
builder.setView(menuView);

Related

how to use prev button and next button change seekbar

In my TopRated.java file, I have an image view which changes when the seekbar is used. It also changes when the next and previous buttons are used. however, i want both buttons and the seeker to be in sync, that is, when the next button is pressed, i want it to also move the seeker up by one, and when the previous button is pressed, i want it to also move the seeker down by one.
please help
This is my TopRated.java file
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
public class TopRated extends Activity {
SeekBar imgseekbar;
ImageView iconimageview;
Button prevbutton;
Button nextbutton;
int progress=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toprated);
iconimageview=(ImageView)findViewById(R.id.imageView);
imgseekbar=(SeekBar)findViewById(R.id.seekBar);
prevbutton=(Button)findViewById(R.id.button8);
nextbutton=(Button)findViewById(R.id.button9);
iconimageview.setImageResource(R.drawable.diablo);
imgseekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateImageResource(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
prevbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress--;
updateImageResource(progress);
}
});
nextbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress++;
updateImageResource(progress);
}
});
}
private void updateImageResource(int progress) {
if (progress==2) {
iconimageview.setImageResource(R.drawable.eye);
}else if (progress==3) {
iconimageview.setImageResource(R.drawable.facebook);
}else if (progress==4) {
iconimageview.setImageResource(R.drawable.google);
}else if (progress==5) {
iconimageview.setImageResource(R.drawable.house);
}else if (progress==6) {
iconimageview.setImageResource(R.drawable.mail);
}else if (progress==7) {
iconimageview.setImageResource(R.drawable.pen);
}else if (progress==8) {
iconimageview.setImageResource(R.drawable.photos);
}else if (progress==9) {
iconimageview.setImageResource(R.drawable.skype);
}else if (progress==10)
iconimageview.setImageResource(R.drawable.twitter);
}
}
This is my toprated.xml file
<?xml version="1.0" encoding="utf-8"?>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:max="10"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_below="#+id/seekBar"
android:layout_centerHorizontal="true"
android:minHeight="50dp"
android:minWidth="50dp"
android:background="#drawable/icon_animation"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prev"
android:id="#+id/button8"
android:layout_alignBottom="#+id/imageView"
android:layout_toStartOf="#+id/imageView"
android:layout_marginRight="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button9"
android:layout_alignBottom="#+id/imageView"
android:layout_toEndOf="#+id/button8"
android:layout_marginLeft="50dp" />
I also have another xml which holds all my images, icon_animation.xml
please help!
any help would be appreciated.
use below line to update seek bar
seekbar.setProgress(int)

Adding dynamic checkboxes android forcecloses Android

i've been trying to make an app with a buttonbar with add/exit buttons at the bottom, and a EditText at the top.
when i hit the add button i want the app to add checkboxes with the text from the EditText.
but when i try to launch the app it force closes.
the logcat show absolutely nothing from my app,
the console says:
[2014-06-24 18:41:06 - CheckList] Starting activity com.pzayx.checklist.CheckList on device 7a0ec297
[2014-06-24 18:41:06 - CheckList] ActivityManager: WARNING: linker: app_process has text relocations. This is wasting memory and is a security risk. Please fix.
[2014-06-24 18:41:06 - CheckList] ActivityManager: WARNING: linker: app_process has text relocations. This is wasting memory and is a security risk. Please fix.
[2014-06-24 18:41:07 - CheckList] ActivityManager: Starting: Intent {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.pzayx.checklist/.CheckList }
[2014-06-24 18:41:07 - CheckList] Attempting to connect debugger to 'com.pzayx.checklist' on port 8960
i cant seem to find much information about "app_process has text relocations. This is wasting memory and is a security risk. Please fix" and suspect the demonspawn lies there.
here is the source of the CheckList.java
package com.pzayx.checklist;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
public class CheckList extends Activity {
LinearLayout lil = (LinearLayout) findViewById(R.id.LinearMain);
EditText mTextInput;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_check_list);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
setupWidgets();
}
private void setupWidgets() {
mTextInput = (EditText) findViewById(R.id.editText1);
Button addBtn = (Button) findViewById(R.id.button_add);
addBtn.setOnClickListener(addListener);
Button exitBtn = (Button) findViewById(R.id.button_exit);
exitBtn.setOnClickListener(exitListener);
}
private OnClickListener addListener = new OnClickListener() {
public void onClick(View v) {
doSaveButtonPress();
}
};
private OnClickListener exitListener = new OnClickListener() {
public void onClick(View v) {
doExitButtonPress();
}
};
public void doSaveButtonPress() {
String text = mTextInput.getText().toString();
CheckBox cb = new CheckBox(getApplicationContext());
cb.setId(i);
cb.setText(text);
lil.addView(cb);
mTextInput.setText("");
i++;
}
public void doExitButtonPress() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
And here is my layout source
<LinearLayout
android:layout_below="#+id/LinearMain"
android:id="#+id/LinearLayoutButtons"
style="?android:buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:divider="?android:attr/dividerVertical"
android:orientation="horizontal"
android:showDividers="middle" >
<!-- <requestFocus /> -->
<Button
android:id="#+id/button_add"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/add"
android:layout_gravity="bottom" />
<View
android:id="#+id/ViewColorPickerHelper"
android:layout_width="1dip"
android:layout_height="40dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dip"
android:layout_marginTop="4dip"
android:background="?android:attr/dividerVertical"
android:layout_gravity="bottom"/>
<Button
android:id="#+id/button_exit"
style="?android:buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/exit"
android:layout_gravity="bottom" />
<!-- Checkbox Area -->
</LinearLayout>
<LinearLayout
android:id="#+id/LinearMain"
android:layout_width="match_parent"
android:layout_height="420dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/editText"
android:ems="10" />
</LinearLayout>
</RelativeLayout>
would appreciate it if anyone could help me make some sense out of it!
Thank you!

Fragment via button

I have a fragment defined in my project plus an activity with a button. What I want is to launch the fragment with that button onclick listener, enter a value in the edit text defined in the fragment's xml layout file and press another button2 present in the fragment. Now what I want is that the button2 return's the text value and open's the activity again. I can then handle what happens to that value.
Java
package com.dreamgoogle.gihf;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class Kahinsebhii extends Fragment {
Button ok;
EditText number;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.kahin, container, false);
ok = (Button) view.findViewById(R.id.button1);
number = (EditText) view.findViewById(R.id.editText1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
number.getText();
}
});
return view;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/kahinbhiedit"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ok" />
</FrameLayout>
Java file to launch the fragment is some other java file.
It sound like what you need is a Dialog. Have a look at the development site: http://developer.android.com/guide/topics/ui/dialogs.html
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();

Need number only soft keyboard?

Hi I need a soft keyboard with only numeric values 0 to 9 and Enter key. Shouldn't show anything other than these like . , ( ) etc...
I tried several options as suggested here but nothings seems to work for me.
setRawInputType(Configuration.KEYBOARD_QWERTY)
setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED)
setRawInputType(InputType.TYPE_CLASS_NUMBER)
setRawInputType(InputType.TYPE_CLASS_PHONE)
I always have the extra characters show up on the keyboard like:
setRawInputType(Configuration.KEYBOARD_12KEY) shows a keyboard like this:
Would appreciate any help. Thanks in advance.
NOTE:
android:minSdkVersion="14": ICS4.0
android:targetSdkVersion="17": JB 4.2
All you can do for standard keyboards is suggest input types. The keyboard can still display or not display whatever keys it wants. If you must have certain keys and only those, you need to create a custom soft keyboard. If it's only for your app, and especially if it's only for one activity, I wouldn't actually implement a standard keyboard, but just use views/buttons that do the appropriate actions.
I've faced the same problem , and i found tat there is no android keyboard like this available
and that the only way is to implement your own.
so i would like to share with you my implement and hopefully save you some valuable time:
i've created this xml , you can modify the colors,fonts and the size of the keyboard accourding to your needs:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<LinearLayout
android:id="#+id/one_to_three"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/one_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"
android:textSize="25sp" />
<Button
android:id="#+id/two_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="2"
android:textSize="25sp" />
<Button
android:id="#+id/three_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="3"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/four_to_six"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/one_to_three"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/four_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4"
android:textSize="25sp" />
<Button
android:id="#+id/five_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="5"
android:textSize="25sp" />
<Button
android:id="#+id/six_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="6"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/seven_to_nine"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/four_to_six"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/seven_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7"
android:textSize="25sp" />
<Button
android:id="#+id/eight_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="8"
android:textSize="25sp" />
<Button
android:id="#+id/nine_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="9"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/zero"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/seven_to_nine"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/zero_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="0"
android:textSize="25sp" />
<Button
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Back"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/done"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/zero"
android:orientation="horizontal" >
<Button
android:id="#+id/done_btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Done"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
i've created this fragment:
package com.galrom.keyboard; //replace it with your package
import com.example.calculator.R;//import your own R class
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnLongClickListener;
import android.widget.Button;
public class KeyBoardFragment extends Fragment {
private Button one_btn;
private Button two_btn;
private Button three_btn;
private Button four_btn;
private Button five_btn;
private Button six_btn;
private Button seven_btn;
private Button eight_btn;
private Button nine_btn;
private Button zero_btn;
private Button back_btn;
private Button done_btn;
private StringBuilder sb;
private onKeyBoardEvent keyboardEventListener;
private int maxLength=10;
private int currentLength;
public static KeyBoardFragment newInstance(String EditTextValue)
{
KeyBoardFragment fragment=new KeyBoardFragment();
Bundle bundle=new Bundle();
bundle.putString("et_value", EditTextValue);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onAttach(Activity activity) {
try{
keyboardEventListener=(onKeyBoardEvent)activity;
}
catch(ClassCastException e)
{
Log.e("ClassCastException in KeyBoardFragment row 50",activity.toString()+" must implement onKeyboardEvent");
e.printStackTrace();
}
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
sb=new StringBuilder(getArguments().getString("et_value"));
currentLength=sb.length();
View rootView=inflater.inflate(R.layout.numeric_keyboard_layout, container, false);
one_btn=(Button)rootView.findViewById(R.id.one_btn);
one_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
add("1");
}
});
two_btn=(Button)rootView.findViewById(R.id.two_btn);
two_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("2");
}
});
three_btn=(Button)rootView.findViewById(R.id.three_btn);
three_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("3");
}
});
four_btn=(Button)rootView.findViewById(R.id.four_btn);
four_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("4");
}
});
five_btn=(Button)rootView.findViewById(R.id.five_btn);
five_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("5");
}
});
six_btn=(Button)rootView.findViewById(R.id.six_btn);
six_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("6");
}
});
seven_btn=(Button)rootView.findViewById(R.id.seven_btn);
seven_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("7");
}
});
eight_btn=(Button)rootView.findViewById(R.id.eight_btn);
eight_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("8");
}
});
nine_btn=(Button)rootView.findViewById(R.id.nine_btn);
nine_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("9");
}
});
zero_btn=(Button)rootView.findViewById(R.id.zero_btn);
zero_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sb.length()>0)
add("0");
}
});
back_btn=(Button)rootView.findViewById(R.id.back_btn);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sb.length()>0)
{
currentLength--;
sb.deleteCharAt((sb.length())-1);
keyboardEventListener.backButtonPressed(sb.toString());
}
}
});
back_btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
currentLength=0;
sb=new StringBuilder();
keyboardEventListener.backLongPressed();
return false;
}
});
done_btn=(Button)rootView.findViewById(R.id.done_btn);
done_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyboardEventListener.doneButtonPressed(sb.toString());
}
});
return rootView;
}
public interface onKeyBoardEvent
{
public void numberIsPressed(String total);
public void doneButtonPressed(String total);
public void backLongPressed();
public void backButtonPressed(String total);
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public void add(String num)
{
currentLength++;
if(currentLength<=maxLength)
{
sb.append(num);
keyboardEventListener.numberIsPressed(sb.toString());
}
else
currentLength--;
}
}
3.the effect of a poping keyboard under the EditText when it is pressed is achived by
creating an empty RelativeLayout that function as an container to the keyboard:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.galrom.keyboard.EditTextNoKeyBoard
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Key_board_container"
android:layout_centerHorizontal="true"
android:clickable="true"
android:ems="10" />
<RelativeLayout
android:id="#+id/Key_board_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:background="#ffffff" >
</RelativeLayout>
when the user press on the EditText the we add the fragment to the container and when he presses done we hide it. the keyboard fragment comunicate with the Activity with the onKeyBoardEvent interace.
NOTE:the hosting activity must implement this interface or else a ClassCastException will be thown.
VERY IMPORTANT: i didn't handled the orientation change, if you change to ladscape while the keyboard is open it will crash, so either disable landscape mode or handle the orientation change to avoid a nullPointerException on the key_board_fragment.
this is the Activity that implemets the keyBoard:
package com.galrom.keyboard;
import com.example.calculator.R;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements KeyBoardFragment.onKeyBoardEvent{
private EditText et;
private KeyBoardFragment keyboard_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.editText1);
et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(keyboard_fragment==null)
{
keyboard_fragment=KeyBoardFragment.newInstance(et.getText().toString());
getSupportFragmentManager().beginTransaction().add(R.id.Key_board_container, keyboard_fragment).commit();
}
else
{
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().hide(keyboard_fragment).commit();
else
{
keyboard_fragment=KeyBoardFragment.newInstance(et.getText().toString());
getSupportFragmentManager().beginTransaction().add(R.id.Key_board_container, keyboard_fragment).commit();
}
}
});
}
#Override
public void numberIsPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
}
#Override
public void doneButtonPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().hide(keyboard_fragment).commit();
}
#Override
public void backLongPressed() {
// TODO Auto-generated method stub
et.setText("");
}
#Override
public void backButtonPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(keyboard_fragment!=null)
{
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().remove(keyboard_fragment).commit();
else
super.onBackPressed();
}
else
super.onBackPressed();
}
}
and the last thing:
to disable the poping of the standart keyboard of android i've created an CustomEditText that simply returns false at: onCheckIsTextEditor() , this is the CustomEditText class:
package com.galrom.keyboard;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
public class EditTextNoKeyBoard extends EditText {
public EditTextNoKeyBoard(Context context) {
super(context);
}
public EditTextNoKeyBoard(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditTextNoKeyBoard(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
// TODO Auto-generated method stub
return false;
}
}
Hope it helped you out...
if you have suggestions for improvement i will be happy to hear.
Gal.
In addition to it set inputType="phone" on the EditText. That will open numeric pad keyboard once you start typing however it will include all extra characters related to the numbers. You would need to implement your own keyboard to keep only the numeric values.
This solution uses numberPassword by overriding the default transformation method for the EditText to show characters instead of dots.
<EditText
android:id="#+id/userid"
android:inputType="numberPassword"
android:maxLength="6"
/>
Add to OnCreate.
// Numeric 6 character user id
EditText input = findViewById(R.id.userid);
// Process input and show characters instead of dots
input.setTransformationMethod(SingleLineTransformationMethod.getInstance());
By default based on your device, the keyboard shows the special characters too in number keyboard . specifying the Keyboard type for the Text field you can achieve the expected result,such as
InputFieldName.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
i.e.
If you need only number included with special characters,then you can use
InputType.TYPE_CLASS_NUMBER
or
if you need to exclude those special characters too then use InputType.TYPE_NUMBER_VARIATION_PASSWORD
i have had the same problem that you have, and just came with a solution, perhaps its not elegant, nor its easy, but it does work splendid...
First of all, the only InputType that works with that keyboard (at least until 4.3) is "numberPassword", but this "hides" your input as dots. so i used that input with this transformation method:
private class ShowNumbersTransformationMethod implements TransformationMethod {
public CharSequence getTransformation(final CharSequence charSequence, final View view) {
return new PassCharSequence(charSequence);
}
#Override
public void onFocusChanged(final View view, final CharSequence charSequence, final boolean b, final int i,
final Rect rect) {
//nothing to do here
}
private class PassCharSequence implements CharSequence {
private final CharSequence charSequence;
public PassCharSequence(final CharSequence charSequence) {
this.charSequence = charSequence;
}
#Override
public char charAt(final int index) {
return charSequence.charAt(index);
}
#Override
public int length() {
return charSequence.length();
}
#Override
public CharSequence subSequence(final int start, final int end) {
return new PassCharSequence(charSequence.subSequence(start, end));
}
}
}
and then set it to your edittext:
edittext.setTransformationMethod(new ShowNumbersTransformationMethod());
Now, as said before, this is not the happiest solution, but i assure you it works like a charm. It would be 10 times easier to create your own custom keyboard, but, i didnt have that option, since my client wanted the standard keyboard, god knows why...
Hope it helped!
The keyboard itself chooses what keys to layout. The best you can do is specify InputType.TYPE_CLASS_NUMBER, but the keyboard will still display whatever it thinks is appropriate to a numeric text field.

close custom Dialog android

I created a custom dialog with spinner and OK button. I have populated this spinner with some items and inflated the layout.If I click OK button dialog will dismiss.
I set the spinner
spinner.performCLick();
is there is any way to get spinner selected item and to close the dialog without pressing OK button. I have tried
button.performclick();
but no use.
see my below code it may help you.
package com.Test_dia;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Test_diaActivity extends Activity {
private Button btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showalert();
}
});
}
protected void showalert() {
// TODO Auto-generated method stub
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.dia);
final String a[] = { "select one", "android", "java", "php" };
Button btnok = (Button) dia.findViewById(R.id.button2);
Spinner spin = (Spinner) dia.findViewById(R.id.spinner1);
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dia.dismiss();
}
});
spin.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, a));
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if (arg2 > 0) {
Toast.makeText(Test_diaActivity.this,
"You Selected :" + a[arg2], Toast.LENGTH_SHORT)
.show();
dia.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dia.show();
}
}
main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here" />
</LinearLayout>
dia.xml
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:text="ok" />
This code is work for me perfectly ok.
enjoy....
EDIT (removed previous non-suitable answer)
I'm going to assume that your issue is that using setOnItemSelectedListener is firing 'onItemSelected' on startup (thus selecting the first item in the spinner without any user input) and you don't want that.
If that is the case, try the following.
Set a class variable:
private int newSpinner = 0;
Then in the setOnItemSelectedListener:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
if (newSpinner != 0) {
// Do your code thing here
dismiss();
} else {
newSpinner++
}
}
});

Categories

Resources