How to know which view was clicked in java? - java

Let's say that I have two ImageViews, and I want to know which one was clicked. How do I use getView() in this case? It's should be something like that
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
checkViewId();
switch(id){
case 1:
log.d -> ("id = 1");
}
break;
case 2:
log.d -> ("id = 2");
break;
return true;
}
How should I create this checkViewId method?

Make your activity/fragment implement the OnClickListener interface and add the onClick callback:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onClick(View v) {
}
}
When you’re binding the views, set the listener for all of them:
ImageView one = (ImageView) findViewById(R.id.one);
one.setOnClickListener(this);
ImageView two = (ImageView) findViewById(R.id.two);
two.setOnClickListener(this);
Inside the onClick method create your switch:
switch (v.getId()) {
case R.id.one:
// add your code
break;
case R.id.two:
// add your code
break;
default:
break;
}

Related

How to get last Fragment used when pressing back button

I have a simple fragment with this code:
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment= null;
switch (menuItem.getItemId()){
case R.id.nav_home:
selectedFragment= new HomeFragment();
setTitle("Beranda");
break;
case R.id.nav_message:
selectedFragment= new MessageFragment();
setTitle("Pesan");
break;
case R.id.nav_transaction:
selectedFragment= new TransactionFragment();
setTitle("Transaksi");
break;
case R.id.nav_profile:
selectedFragment= new ProfileFragment();
setTitle("Profil");
if(sessionLevel.equals("admin")){
setTitle("Admin");
}
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
Most of the fragment are just some kind of holder for Intent Activity. And the Activity itself doesnt have some fancy code.
The problem is that when i do Intent on Profile menu and then press back, the fragment shown is HomeActivity but the selected button is Profile.
I dont know about the other 2 fragment since im not there yet, but probably they do the same thing.
You can do this like the following:
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment frag = YourActivity.this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(frag!=null && frag instanceof yourFragment)
{}
}
The following will give you count
int count = getSupportFragmentManager().getBackStackEntryCount();
You can make condition, If count is great than 1 then have more than 1 fragments else you have atleast 1 fragment and that will be last fragment. If count 0 then no more fragment available on stack as all have been poped out of stack.
Create an interface:
public interface IOnBackPressed {
boolean onBackPressed();
}
In Fragment implement IOnBackPressed like:
public class FAQFragment extends Fragment implements IOnBackPressed {
public boolean onBackPressed() {
return false
}
}
On Main Activity Backpress use
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
}

TextViews and Intents problems

I have 40 textviews but I want to know which one was pressed so that it takes me to the desired Intent. How do I implement this ?
Implement onClickListener for all the TextViews. And handle the clicks according to TextView IDs in your listener. Its same as you handle onClick for a single textView.
In your listener use:
public void onClick(View view) {
switch(view.getId()) {
case R.id.textView1:
break;
case R.id.textView2:
break;
}
}
Adding an OnClickListener for all the views can be cumersome. The best way is probably a better way of laying these textView out. Probably a ListView or some implementation of RecyclerView.
But just as an answer to your question, make your class implement View.OnClickListener and check the id of the clicked View in the onClick method.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.textView1:
// code here
break;
case R.id.textView2:
//code here
break;
}
}
}

Android If statement for multiple setOnClickListener

I have multiple setOnClickListener and what I want to do is, to make it more simple.
Here's my java
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// get the button view
ImageView foodImg = (ImageView) getView().findViewById(R.id.iconFoods);
ImageView barsImg = (ImageView) getView().findViewById(R.id.iconBars);
ImageView roomsImg = (ImageView) getView().findViewById(R.id.iconRooms);
ImageView wellnessImg = (ImageView) getView().findViewById(R.id.iconWellness);
ImageView beachesImg = (ImageView) getView().findViewById(R.id.iconBeaches);
ImageView kidsImg = (ImageView) getView().findViewById(R.id.iconKids);
ImageView attractionsImg = (ImageView) getView().findViewById(R.id.iconAttractions);
ImageView shopsImg = (ImageView) getView().findViewById(R.id.iconShops);
ImageView museumsUmg = (ImageView) getView().findViewById(R.id.iconMuseum);
// set a onclick listener for when the food button gets clicked
foodImg.setOnClickListener(new OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
Food.class);
startActivity(mainIntent);
}
});
// set a onclick listener for when the bars button gets clicked
barsImg.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
Bars.class);
startActivity(mainIntent);
}
});
As you can see I create one setOnClickListener for each ImageView.
My Question is, how to use if statement for multiple setOnClickListener?
So when I click ImageView Foods Icon I open the foods activity.
Thanks before :D
Create a common onClickListener
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.button1:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 1 pushed");
break;
case R.id.button2:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 2 pushed");
break;
case R.id.button3:
((TextView) getView().findViewById(R.id.textView1)).setText("Button 3 pushed");
break;
}
}
};
Then set each View to use that click listener, i.e:
Button btn1 = (Button) getView().findViewById(R.id.button1);
Button btn2 = (Button) getView().findViewById(R.id.button2);
Button btn3 = (Button) getView().findViewById(R.id.button3);
btn1.setOnClickListener(onClickListener);
btn2.setOnClickListener(onClickListener);
btn3.setOnClickListener(onClickListener);
Hope it helps.
Used Switch Case for that in onClick(...) like
public void onClick(View v) {
switch (v.getId()) {
case R.id.iconFoods:
//do your Intent
break;
case R.id.iconBars:
//do your Intent
break;
case R.id.iconRooms:
break;
case R.id.iconWellness:
//do your Intent
break;
case R.id.iconBeaches:
//do your Intent
break;
and so on....
}
}
But for this your Activity or Fragment must extends onClickListener Interface
public class MyFragment extends Fragment implements OnClickListener {
and you'll set this Listener to your ImageView like:
foodImg.setonClickListner(this);
roomsImg.setonClickListner(this);
...and so on
Assign the same listener to all of the views.
foodImg.setOnClickListener(this);
Then implement the listener interface in your Fragment.
public class MyFragment extends Fragment implements OnClickListener {
and add the onClick() method to your Fragment:
public void onClick(View v) {
switch (v.getId())
{
case R.id.iconBars:
// handle the click
break;
case R.id.iconMuseum:
// handle the click
break;
// add all the other cases here
}
}
Implement OnClickListener to your activity , just like this:-
public class MyActivity extends Activity implements OnClickListener
After Implementing it will ask you to add umimplemented method, then on that method you can use switch case just like following
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.foodImg :
break;
default:
break;
}
}
And dont forget to assign the same listener to all of the views.
For that you can make an method and call it on the OnCreate method
private void registrerListeners() {
foodImg.setOnClickListener(this);
//rly add rest oncliclisterner of your image
}

Navigation Drawer not working when startActivity is used in first case of selectItem

I have this problem with Google's Navigation Drawer where starting the activity specified in the first case (case 0) in my selectItem method breaks and returns to the previous activity.
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch(position) {
case 0:
// Placing any startActivity here will load the activity
// but immediately return to the calling activity.
parent.startActivity(new Intent(parent, Dashboard.class));
break;
case 1:
parent.startActivity(new Intent(parent, Card.class));
break;
}
}
But if I put mDrawerLayout.closeDrawer(mDrawerList); or any other code, it'll work normally.
There are no errors reported when the called activity is closed and no exception is thrown. Any thoughts?
I tried reproducing this and it will not resolve parent. Do you have it declared somewhere else ?
What class are you using this in both Activities and Fragments can use startActivity() without the need for parent.startActivity()
Can you post the complete class?
This works for ok for me.
private void selectItem(int position) {
switch (position) {
case 0:
// goto home screen
Log.d(TAG, "Showing Home");
startActivity(new Intent(this, SettingsActivity.class));
break;
case 1:
// Show Editor
Log.d(TAG, "Showing Editor");
break;
default:
break;
}
}

AutoComplete fixed selection?

How do i have an AutoComplete selection based on alphabetic instead of fixed switch cases? The situation is, everything working except when i input keyword with "B" showing Badrul as first suggestion but when clicked it will still refer to the first switch cases which is opening up Adidas.class instead of Badrul.class
Please help, i am new in this. Is AutoComplete suitable for my requirement?
public class Search extends Activity
{
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoComplete.setAdapter(adapter);
autoComplete.setThreshold(1);
autoComplete.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
switch(position)
{
case 0:
startActivity(new Intent(Search.this, Adidas.class));
break;
case 1:
startActivity(new Intent(Search.this, Affin.class));
break;
case 2:
startActivity(new Intent(Search.this, AlamArt.class));
break;
case 3:
startActivity(new Intent(Search.this, Badrul.class));
break;
}
}
});
}
static final String[] shops = new String[]
{
"Adidas", "Affin Bank", "Alam Art Gallery", "Badrul"
};
}
You are adding OnItemClickListener to the AutoCompleteTextView. I think you don't know this thing about Item Click Listener.
The position variable in onItemClick() method stores the position of item clicked in the list shown.
You are telling the list shown Badrul as first suggestion, so the position of item you clicked is 0, so that its going to case 0:, so that its calling Adidas.class.
I hope you understood the problem from my answer.
This is obvious behavior as you are referring to the position of the suggestion at current time,so it would be differed according to what user types in. For achieving what you want,You need to change your code according to this:
public class Search extends Activity
{
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
final AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoComplete.setAdapter(adapter);
autoComplete.setThreshold(1);
autoComplete.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
int index=999;
for(int i=0;i<shops.length;i++)
{
if(autoComplete.getText().toString().trim().equals(shops[i]))
{
index=i;
break;
}
}
switch(index)
{
case 0:
startActivity(new Intent(Search.this, Adidas.class));
break;
case 1:
startActivity(new Intent(Search.this, Affin.class));
break;
case 2:
startActivity(new Intent(Search.this, AlamArt.class));
break;
case 3:
startActivity(new Intent(Search.this, Badrul.class));
break;
default:
Toast.makeText(Search.this, "Invalid Selection", Toast.LENGTH_SHORT).show();
}
}
});
}
static final String[] shops = new String[]
{
"Adidas", "Affin Bank", "Alam Art Gallery", "Badrul"
};
}
Mr. Kenneth The solution is already there, Hiral's answer, but you have to modify it, to make error free.
Just do below changes.
Modify the below line of code into 2 parts.
AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
1. Add below line of code before onCreate()
AutoCompleteTextView autoComplete;
2.Modify the original line as below
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);

Categories