Android: Broken menu button when text used - java

I have defined a standard onCreateOptionsMenu. The menu button works fine when my EditText box is empty. But when the EditText box has data in it, the menu button doesnt work. Any clue? Please help, i have no clue how to solve this. Thanks!
public class TipCalc extends Activity {
private EditText total;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
total = (EditText)findViewById(R.id.EditText01);
total.setOnKeyListener(mKeyListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
private OnKeyListener mKeyListener = new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if((v.getId() == R.id.EditText01
&& (total.getText().toString().length() > 0) {
calculate();
return true;
}
}
return false;
}
}

I dont know if that would be correct but create setOnClickListener rather than OnKeyListener
something like this
TextView total = (TextView) findViewById(R.id.EditText01);
total.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//do some stuff
}
});

Related

How to access an options menu item from outside the menu

How can an options menu item be accessed from an object outside of the menu itself? I'm trying to set an alpha value for one of the options menu items, but it's not working for some reason. The commented lines are what I tried.
I've seen the following code used before, but it's not clear on where and how it should be used:
Drawable drawable = item.getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setAlpha(1);
}
Activity class
public class WebviewActivity extends AppCompatActivity {
private static final String TAG = WebviewActivity.class.getSimpleName();
WebView myWebView;
ProgressBar myProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_webview);
}
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fragment_webview);
String url = getIntent().getStringExtra("url");
myWebView = findViewById(R.id.web_view);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
}
});
}
private class WebViewClient extends android.webkit.WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
String url=request.getUrl().toString();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
public void onBtnBackPressed() {
if (myWebView.canGoBack()){
myWebView.goBack();
} else {
onBackPressed();
}
}
public void onBtnForwardPressed() {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
// menu.getItem(R.id.action_webbrowser_forward).setEnabled(false);
// menu.getItem(R.id.action_webbrowser_forward).mutate();
// menu.getItem(R.id.action_webbrowser_forward).setAlpha(1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.web_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed();
}
return super.onOptionsItemSelected(item);
}
}
Define in your activity class this variable:
MenuItem action_webbrowser_forward;
In onCreateOptionsMenu() after the inflation of the menu, write this:
action_webbrowser_forward = menu.findItem(R.id.action_webbrowser_forward);
then you can use it anywhere in your class:
action_webbrowser_forward.setEnabled(false);
but mutate is used for drawables and not menu items, so get the icon of the item by action_webbrowser_forward.getIcon() and apply mutate to it.
Try passing MenuItem reference on your onBtnForwardPressed function parameters :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed(item);
}
return super.onOptionsItemSelected(item);
}
And :
public void onBtnForwardPressed(MenuItem menuItem) {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
menuItem.setEnabled(false);
menuItem.getIcon().setAlpha(50);
}
}
Hope this helps
Okay I spend couple of hour to get this solution.apparently you can get menuitem from your toolbar. So in my case.
var menuItem = toolbar.menu;
Now to get specfic item from menu item
favIcon = menuItem.findItem(R.id.favourite);
Note: favIcon is MenuItem declare global
Now if you can do whatever you want to do for this icon
eg. to make it invisible
favIcon?.isVisible=false

How to get Background from another Activity?

I want to change the background-color of another Activity (start) in my Settings-Activity (choose between different colors, sounds etc.).
How can I change the color of another Activity?
I tried to get the Background from my start-Activity (id:start) with:
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
but it seems it doesn´t work.
Full Code of the Settings-Activity:
public class activity_settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_settings);
ColorChange();
}
public void ColorChange() {
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
final RadioButton ChangeToBlue = (RadioButton) findViewById(R.id.button_blue);
final RadioButton ChangeToRed = (RadioButton) findViewById(R.id.button_red);
final Button button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ChangeOption(background);
}
});
ChangeToBlue.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToBlue(background);
}
});
ChangeToRed.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToRed(background);
}
});
}
public void ChangeOption(RelativeLayout background) {
if (background.isEnabled()) {
background.setEnabled(false);
} else {
background.setEnabled(true);
}
}
public void ChangeToBlue(RelativeLayout background) {
background.setBackgroundColor(Color.BLUE);
background.invalidate();
}
public void ChangeToRed(RelativeLayout background) {
background.setBackgroundColor(Color.RED);
background.invalidate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_settings, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
Save color code i.e. #F0F0F0 from your setting-activity in a sharedPreference and get this value in onCreate() of activity in which you want to set background.

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.

Radio Group as Circular Page Indicator

I am trying to use RadioGroup as a CircularPageIndicator. The problem is with the RadioGroup.OnCheckedChangeListener. It seems to call it self when onPageSelected is called. However I want it to work vice versa i.e. when I select a radioButton it should change a view based on the location of the Array index being provided. However it seems as if onCheckedChange is never called when I change a check on the radio button and so onCheckedChange never triggers.
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener, OnPageChangeListener {
ViewPager mImagePager;
ImagePagerAdapter mPagerAdapter;
RadioGroup mPageIndicator;
boolean swipeChange = false;
int[] mRadioButtonIds = new int[] { R.id.radio0, R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponents();
mPageIndicator.setOnCheckedChangeListener(this);
mImagePager.setAdapter(mPagerAdapter);
mImagePager.setOnPageChangeListener(this);
}
/**
*
*/
private void initComponents() {
mPageIndicator = (RadioGroup) findViewById(R.id.radioGroup1);
mImagePager = (ViewPager) findViewById(R.id.imgPager);
mPagerAdapter = new ImagePagerAdapter();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int pSelectedPagePosition) {
swipeChange = true;
mPageIndicator.check(mRadioButtonIds[pSelectedPagePosition]);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (!swipeChange) {
int itemPosition = Arrays.asList(mRadioButtonIds).indexOf(checkedId);
mImagePager.setCurrentItem(itemPosition, true);
swipeChange = false;
}
}
}
Note : I don't want to use any third party code/lib to create a custom Circular Page Indicator.
Can any one please point a mistake here. Is there a reason for the RadioGroup not to work?
I forgot to take a look at the documentation!
http://developer.android.com/guide/topics/ui/controls/radiobutton.html

How to enable the sound effect on touching a button?

If I implement the OnClickListener, the sound effect will work on clicking the button. While on implementing the OnTouchListener the sound effect doesn't work on touching it. So how to enable the sound effect on implementing the OnTouchListener?
EDIT:
Here is the code if I use clicking approach:
public class CalculatorActivity extends Activity implements OnClickListener
{
//...
private Button btn1;
private EditText edLCD;
//...
public void onCreate(Bundle savedInstanceState)
{
//...
btn1 = (Button) findViewById(R.id.d1);
btn1.setOnClickListener(this);
edLCD = (EditText) findViewById(R.id.edLCD);
}
//...
public void onClick(View v)
{
edLCD.setText(edLCD.getText().toString() + "1");
}
}
And here is the code if I use touching approach:
public class CalculatorActivity extends Activity implements OnTouchListener
{
//...
private Button btn1;
private EditText edLCD;
//...
public void onCreate(Bundle savedInstanceState)
{
//...
btn1 = (Button) findViewById(R.id.d1);
btn1.setOnTouchListener(this);
edLCD = (EditText) findViewById(R.id.edLCD);
}
//...
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
edLCD.setText(edLCD.getText().toString() + "1");
}
return true;
}
}
Try...
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
v.playSoundEffect(SoundEffectConstants.CLICK);
edLCD.setText(edLCD.getText().toString() + "1");
}
return true;
}

Categories

Resources