I would like to detect single taps several times. I have an activity where the user can tap on an image, they should receive the Toast message, and the program should change the image to another one, and whenever the user taps on this image, there's should be another Toast message. To be more specific, I'll try to provide an example:
Let's say we have two images:
1 - straight line
2 - circle
when the user will enter the specified activity, should see one of those images in the toolbar (let's say that first of them are straight line). When the user will click on this image, the app should display Toast, and then change the straight line to a circle.
*By changing images I mean setting method like
circle.setVisibility(View.VISIBLE); // circle.setVisibility(View.GONE);
Unfortunately, my switch case doesn't work as I intended. Whenever a user clicks on the first image, it's changing the visibility of those two, but look's like the OnClick method doesn't recognize another tap. Here's the code
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.line: {
Toast.makeText(TAG.this, "line", Toast.LENGTH_SHORT).show();
test = 2;
break;
}
case R.id.circle: {
Toast.makeText(TAG.this, "circle", Toast.LENGTH_SHORT).show();
break;
}
}
switchImages();
}
private void switchImages(){
switch (test){
case 1:
line.setVisibility(View.GONE);
circle.setVisibility(View.VISIBLE);
break;
case 2:{
line.setVisibility(View.VISIBLE);
circle.setVisibility(View.GONE);
break;
}
}
}
You missed something.. ;)
public void onClick(View v) {
switch (v.getId()) {
case R.id.line: {
Toast.makeText(TAG.this, "line", Toast.LENGTH_SHORT).show();
test = 2;
break;
}
case R.id.circle: {
Toast.makeText(TAG.this, "circle", Toast.LENGTH_SHORT).show();
break;
}
}
switchImages();
}
In the first case you are assigning test = 2 but in the second one you don't do anything with that variable, so method switchImages() won't really do anything, since it depends on test which is 2 all the time (images will not switch accordingly)
You are initializing test in first case as test = 2 but forget to initialize it in second case
So just change the code :
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.line: {
Toast.makeText(TAG.this, "line", Toast.LENGTH_SHORT).show();
test = 2;
break;
}
case R.id.circle: {
Toast.makeText(TAG.this, "circle", Toast.LENGTH_SHORT).show();
test = 1;
break;
}
}
switchImages();
}
I would have changed only onClick(View v) and removed switchImages();
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.line: {
Toast.makeText(TAG.this, "line", Toast.LENGTH_SHORT).show();
line.setVisibility(View.GONE);
circle.setVisibility(View.VISIBLE);
break;
}
case R.id.circle: {
Toast.makeText(TAG.this, "circle", Toast.LENGTH_SHORT).show();
line.setVisibility(View.VISIBLE);
circle.setVisibility(View.GONE);
break;
}
}
}
As per your question, if you click line, it will toast and make visible circle and hide line and vice-versa
Related
I am coding in Java in Android Studio and I am currently making an Calendar app that save, show, edit events. I had to put some view, like MonthView WeekView and DailyView. At first I made it in a way so all of them were activities and when i want to go back the back pressed button almost done my job. Because of some odds, I turned out to keep only one activity and do the same job with some methods instead of making activities. I have a navigation drawer, so in onItemNavigationClick the user can select which view want. So, my problem is that I cant find a way to act the previous method, like if I go to WeekView and press backButton, get back in Month or in Daily view.
As I see backpressed is to go back an activity, so I think it cant help me. I would apreciate any help.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSchedule:
setAllEvents();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.daysView:
setDaily();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.weekView:
setWeek();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.monthView:
setMonthView();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.refreshItem:
finish();
startActivity(getIntent());
break;
case R.id.syncItem:
break;
default:
onNavigationItemSelected(item);
}
return true;
}
Example of how my set Methods are working:
private void setMonthView() {
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray();
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this, getApplicationContext());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
ViewGroup.LayoutParams params = calendarRecyclerView.getLayoutParams();
params.height=1500;
calendarRecyclerView.setLayoutParams(params);
monthListView.setVisibility(View.GONE);
monthYearText.setVisibility(View.VISIBLE);
daysOfWeekDaily.setVisibility(View.GONE);
daysOfWeek.setVisibility(View.VISIBLE);
prevMonth.setVisibility(View.VISIBLE);
nextMonth.setVisibility(View.VISIBLE);
calendarRecyclerView.setVisibility(View.VISIBLE);
nestedScrollView.setVisibility(View.VISIBLE);
}
SOLUTION
Thanks to David Wesser, the code works in the way I want to, here source code of my problem:
public void onMyBackPressed() {
// Pop current view type off the stack
stack.removeFirst();
// Check the previous view type
String previousViewType = stack.peekFirst();
if (previousViewType == null) {
// Nothing to go back to, so finish this Activity
super.onBackPressed();
return;
}
if (previousViewType.equals("daily")) {
setDaily();
} else if (previousViewType.equals("week")) {
setWeek();
} else if (previousViewType.equals("all"))
{
setAllEvents();
}else if (previousViewType.equals("month"))
{
setMonthView();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSchedule:
setAllEvents();
stack.addFirst("all");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.daysView:
setDaily();
stack.addFirst("daily");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.weekView:
setWeek();
stack.addFirst("week");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.monthView:
setMonthView();
stack.addFirst("month");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.refreshItem:
finish();
startActivity(getIntent());
break;
case R.id.syncItem:
break;
default:
onNavigationItemSelected(item);
}
return true;
}
You can do this by building a stack that represents the type of view you are showing. Whenever the user selects something from the navigation drawer, you call the method to show that view and you push something on the stack (a String or an Integer constant) that represents the kind of view you are showing. Then override onBackPressed() so that instead of the default behaviour (which is to finish the current Activity and return to the previous Activity), you so something like this:
Pop off the last thing from your stack (this represents the currently shown view)
If there is nothing left on the stack, you should call the default behaviour with super.onBackPressed(), which will send the user back to the HOME screen or whatever
Otherwise, examine the topmost thing on the stack (this represents the previously shown view) and use it to call the appropriate method to show the view that it represents. In this case remember not to push a new thing onto the stack because the top item on the stack already represents the view that is being shown.
Code Example:
// Declare the stack as a member variable in the Activity
ArrayDeque<String> stack = new ArrayDeque<String>();
inside your switch statement, something like this for each different view type:
case R.id.daysView:
setDaily();
// push the current view type onto the stack
stack.addFirst("day");
case R.id.weekView:
setWeek();
// push the current view type onto the stack
stack.addFirst("week");
etc...
Now override the behaviour of onBackPressed():
#Override
public void onBackPressed() {
// Pop current view type off the stack
stack.removeFirst();
// Check the previous view type
String previousViewType = stack.peekFirst();
if (previousViewType == null) {
// Nothing to go back to, so finish this Activity
super.onBackPressed();
return;
}
if (previousViewType.equals("day")) {
setDaily();
} else if (previousViewType.equals("week")) {
setWeekly();
} else ... // rest of the view types here
}
I am trying to use a GitHub library (MeowBottomNavigation)in Android Studio.But its written in kotlin and i cant use the listeners in it.
The only thing which is given is this
bottomNavigation.setOnShowListener {
}
bottomNavigation.setOnClickMenuListener {
}
the suggestions shows to use
(Function1)
i am not sure as to how to implement this in java . Any help will be appreciated.
I am familiar with java but the library is written in Kotlin. Is there any way to use these listeners in java?
bottomNavigation.setOnClickMenuListener(new
Function1<MeowBottomNavigation.Model, Unit>() {
#Override
public Unit invoke(MeowBottomNavigation.Model p1) {
int i = p1.getId();
switch (i){
case 4:
Toast.makeText(UserMainActivity.this, i, Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(UserMainActivity.this, i, Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(UserMainActivity.this, i, Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(UserMainActivity.this, i, Toast.LENGTH_SHORT).show();
break;
}
return Unit.INSTANCE;
}
});
Function0, Function1, Function2, ... FunctionN are higher-order functions in kotlin.
After converting to java, your click listeners become something like below.
// Set Menu Click Listener
bottomNavigation.setOnClickMenuListener(new Function1<MeowBottomNavigation.Model, Unit>() {
#Override
public Unit invoke(MeowBottomNavigation.Model p1) {
return Unit.INSTANCE;
}
});
// Set Menu Show listener
bottomNavigation.setOnShowListener(new Function1<MeowBottomNavigation.Model, Unit>() {
#Override
public Unit invoke(MeowBottomNavigation.Model s) {
return Unit.INSTANCE;
}
});
something like This::
bottomNavigation.setOnShowListener( new IBottomNavigationListener(Model model)
{
} );
if you are using fragments
//1.-declare fragments globally in your activity
private HomeFragment homeFragment = new HomeFragment();
//2.- declare a method to switch between fragments
public void loadFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.yourFragmentContainer,fragment);
transaction.commit();
}
//3.- in the Set Menu Click/show Listener call the fragment to show
// Set Menu Click Listener
bottomNavigation.setOnClickMenuListener(new Function1<MeowBottomNavigation.Model, Unit>() {
#Override
public Unit invoke(MeowBottomNavigation.Model model) {
int i = model.getId();
switch (i){
case 1:
loadFragment(homeFragment);
break;
//...other cases
}
return Unit.INSTANCE;
}
});
// Set Menu Show listener
bottomNavigation.setOnShowListener(new Function1<MeowBottomNavigation.Model, Unit>() {
#Override
public Unit invoke(MeowBottomNavigation.Model model) {
int i = model.getId();
switch (i){
case 1:
loadFragment(homeFragment);
break;
//...other cases
}
return Unit.INSTANCE;
}
});
use
implementation 'com.etebarian:meow-bottom-navigation-java:1.2.0'
for details watch
https://www.youtube.com/watch?v=MiphbOtSyWY
I'm working on a soundboard and I want to implement a long click to share the sound.
I am working with a switch Case for each button
public void MainMMP(View view){
switch (view.getId()) {
case R.id.button1:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx1);
MainMMP.start();
break;
case R.id.button2:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx2);
MainMMP.start();
break;
case R.id.button3:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx3);
MainMMP.start();
break;
And now I want to implement the long click. I tried a lot of different code here but it is not working for me.
I do not know where to put the onLongClick statement and how.
Can somebody show me a working method and in case of long click it should just send me a Toast that I know the method works?
You could add the OnLongClickListener where you want, in the onCreate method for example.
Try to use the following code:
Button button = (Button)findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Your code
return false; // True if you want to execute simple click code too
}
});
You can use this
private View.OnLongClickListener listener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
switch (view.getId())
case R.id.button1:
// Do something...
break;
case R.id.button2:
// Do something else...
break;
// If you still want to get normal click callbacks return true,
// if you do not then return false.
return true;
}
}
Somewhere in your code
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
Or better this
One common recommended way to get onClick/onLongClick/whatever callbacks is to make the Activity implement the callback interfaces.
class YourActivity extend Activity implements View.OnLongClickListener {
#Override
public boolean onCreate(/* ... */) {
// ...
button1.setOnLongClickListener(this);
button2.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
// Same code as the one above
}
}
I've just started out in Java programming and am having a bit of trouble implementing an OnClickListener switch case for my clickable TextViews. I've managed to make a switch case for menu items, but i'm obviously not understanding it enough to make a more general case.
Here's the bits of my code that are important to it
public class MyActivity extends Activity implements SensorEventListener {
TextView tv, tv1, tv2, tv3;
#Override
public void onCreate(Bundle savedInstanceState) {
//get textviews
tv = (TextView) findViewById(R.id.xval);
tv1 = (TextView) findViewById(R.id.yval);
tv2 = (TextView) findViewById(R.id.zval);
tv3 = (TextView) findViewById(R.id.scalar);
And then I setup individual on click listeners for each TextView, e.g.
tv1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do things
}
}
});
But i'm trying to set it up so i have a a combined OnClickListener, like:
#Override
public boolean onClickListener (View v) {
switch (tv.findViewById()) {
case tv:
//Do things
return true;
case tv1:
//Do things
return true;
case tv2:
//Do things
return true;
case tv3:
//Do things
return true;
}}
I'm aware that code is very wrong, but i can't seem to wrap my head around it. I've already assigned my findViewById so i'm not sure what else to put into the switch!
Thankyou!
I'll provide an alternative answer. First you have to create an OnClickListener, which will receive your OnClick events:
OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.xval:
//code
break;
case R.id.yval:
//code
break;
case R.id.zval:
//code
break;
case R.id.scalar:
//code
break;
default:
break;
}
}
};
Then, you have to associate that listener to every TextView you have:
tv.setOnClickListener(listener);
tv1.setOnClickListener(listener);
tv2.setOnClickListener(listener);
tv3.setOnClickListener(listener);
Once you click one of the TextViews, your OnclickListener onClick() callback will be called and it will check the TextView id you have clicked and run the code accordingly, dependeing on the case.
tv.setOnClickListener(this);
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
tv3.setOnClickListener(this);
#Override
public boolean onClick (View v) {
switch (v.getId()) {
case R.id.xval:
//Do things
return true;
case R.id.yval:
//Do things
return true;
case R.id.zval:
//Do things
return true;
case R.id.scalar:
//Do things
return true;
}}
Create one listener, add it to all TextView. Switch on the view id, which is a simple int
View.OnClickListener listener = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId()) {
case R.id.xval:
//Do things
return true;
case R.id.yval:
//Do things
return true;
case R.id.zval:
//Do things
return true;
case R.id.scalar:
//Do things
return true;
}
}
};
tv.setOnClickListener(listener);
tv1.setOnClickListener(listener);
tv2.setOnClickListener(listener);
tv3.setOnClickListener(listener);
OK my question is a lot bigger than the Title. But can't describe everything in a Title. So here we go.
I am writing an App that when a NFC cards get detected by Phone, it will be able to WRITE and READ a NDEF message on / from it.
I use two buttons READ and WRITE to trigger these events. Everything works fine, just the thing that EVERYTHING REPEATS ITSELF FOUR (4x) TIMES!
Only the TAG "UltraLightCard Detected" and "Connected" pops once.
Everything else that you see in code in "ShowMessage" will pop out 4x times also the AlertDialog box gets triggered 4x times and you have to write the text 4 times.
If you wrote it only once and then clicked "Save" 3x times just to close it, it wont store the string.
Here's my code:
protected void ultralightCardLogic() {
final Button b_write = (Button)findViewById(R.id.b_write);
final Button b_read = (Button)findViewById(R.id.b_read);
b_write.setId(1);
b_read.setId(2);
//showImageSnap(R.drawable.ultralight);
ShowMessage("UltraLight Card Detected :" + mifareUL.getTagName(), 'a');
try {
mifareUL.connect();
mifareUL.formatT2T();
ShowMessage("Connected!" , 'd');
b_write.setOnTouchListener(new MyTouchListener());
b_read.setOnTouchListener(new MyTouchListener());
} catch (IOException e) {
e.printStackTrace();
}
}
Here is MyTouchListener:
public class MyTouchListener implements OnTouchListener{
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stu
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
return false;
}
}
Here is the OnCreateDialog:
final View v = getLayoutInflater().inflate(R.layout.dia_box,null);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setView(v)
.setPositiveButton("SAVE", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
final EditText mEdit=(EditText)v.findViewById(R.id.et_dia);
String str = mEdit.getText().toString();
writeNDEFmsg(str);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
If you guys need some more of the code, I can add it then. Don't want to write too much code, because my experience tells me that then noone will try to help me out.
Please, help me out
Thanks to your help I figured out my issue.
I used onTouchListener, which triggers more than once, since it has more MotionEvents available.
After I changed on to OnClickListener everything works smoothly!
Just be sure to implement View.OnClickListener
if you are doing it like I do in my public class MyClickListener.
Then Eclipse will auto-generate your necessary code. Extract the id of your buttons and do the switch statement (again, if you`re doing it this way):
public class MyClickListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
}
Thanks again for the help! Hope it will help someone else too.