Button OnClick from Fragment to MainActivity - java

I have 3 Fragments inside my MainActivity and in one of my Fragments I have 3 ImageView and each of image view performs same action based on which ImageView was selected, now What I want to achieve is that instead of using OnClickListener for each of Views separately, call same method with switch-case or if-else inside. But the problem is those ImageViews inside fragment cannot call Functions implemented inside MainActivity. for instance. here's the code to understand what I want to say:
MAIN ACTIVITY
public void imageClicked(View v){
if(v.getID() == findViewById(R.id.id_of_imageView_1).getID()){
myTextView.setText("ImageView 1 is Clicked")
}
else if(v.getID() == findViewById(R.id.id_of_imageView_2).getID()){
myTextView.setText("ImageView 2 is Clicked")
}
else if(v.getID() == findViewById(R.id.id_of_imageView_3).getID()){
myTextView.setText("ImageView 3 is Clicked")
}
}
XML (fragment_images.xml) WHERE IMAGES EXIST
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/id_of_imageView_1"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:src="#drawable/laptop" />
<ImageView
android:id="#+id/id_of_imageView_2"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:src="#drawable/memory" />
<ImageView
android:id="#+id/id_of_imageView_3"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:src="#drawable/screen" />
</LinearLayout>
</ScrollView>
XML (activity_main.xml) HERE I Link my Fragment and TextView
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
//CHANGE THIS TEXT VIEW WHEN IMAGE IS CLICKED
<TextView
android:id="#+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:text="Select Product"
android:textSize="20sp"
android:textStyle="bold" />
<fragment
android:id="#+id/fragment_1"
android:name="com.salmanibrahim.calssifiedelectronics.ListFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_list" />
<fragment
android:id="#+id/fragment_2"
android:name="com.salmanibrahim.calssifiedelectronics.DetailFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_detail" />
//THIS IS THE FRAGMENT
<fragment
android:id="#+id/fragment_images"
android:name="com.salmanibrahim.calssifiedelectronics.AddProduct"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_images" />
</LinearLayout>
How do I call imageClicked() defined inside MainActivity using onClick on ImageView

In your fragment you can call imageClicked() in the MainActivity by using requireActivity() or getActivity() and do the necessary cast
In fragment:
public View onCreateView(...) {
View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
MainActivity mActivity = (MainActivity) requireActivity();
imageView1 = view.findViewById(...);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.imageClicked(imageView1);
}
});
...}
repeat the same for imageView2, 3
Also the condition in imageClicked() seems not right as you findViewById which will point to your MainActivity layout, not the fragment.
So you need to change this
if (v.getID() == findViewById(R.id.id_of_imageView_1).getID())
To
if (v.getID() == R.id.id_of_imageView_1)
And do the same for other images.

I understand what you trying to do but android:onClick parameter only links for the context declared in tools:context field on the parent tag of your layout file.
So it is not possible to reference your imageClicked() function found in your MainActivity from your fragment's ImageView because they are in different context. Check this for more info.

You are doing it in wrong way.
You can do this instead.
imageView_1.setOnClickListener(this);
then implement activity from View.onClickListener
then get view by id on the method that's been implemented.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.id_of_imageView_1:
// do your things here
break;
}
}

Related

When Onclick operates in fragment xml, app crashes

I'm new to the development scene and I'm just trying my hand at fragments. I have an onClick event defined in one of my fragment XML files, but when I click the button my app crashes.
I've surmised that this happens because my onClick event is defined in my fragment and not my MainActivity, so I was just wondering what is the best practice to get my buttons working. Should I just pass the button along to my fragment, or should I move my onClick event to my MainActivity then reference it from my fragment?
***************** this is the code ****************
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_weight="1.5">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginRight="5dp"
android:gravity="right"
android:layout_weight="2">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="150dp"
android:id="#+id/txt_textInputLayout_three"
android:layout_height="wrap_content"
app:startIconDrawable="#drawable/ic_baseline_calendar_today_24">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/txt_from_user1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="From"
android:onClick="openDataPicker_from"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginLeft="5dp"
android:gravity="left"
android:layout_weight="2">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="150dp"
android:id="#+id/txt_textInputLayout_four"
android:layout_height="wrap_content"
app:startIconDrawable="#drawable/ic_baseline_calendar_today_24">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/txt_to_user1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"
android:onClick="openDatePicker_to"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</LinearLayout>
Java file***
public void openDatePicker_from(View view) {
dataPickerDialog_from.show();
}
public void openDatePicker_to(View view) {
dataPickerDialog_to.show();
}
this the error
java.lang.IllegalStateException: Could not find method openDataPicker(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.textfield.TextInputEditText with id 'txt_from_user1'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:5368)
It worked, Try this
FromDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPickerDialog_from.show();
}
});
ToDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPickerDialog_to.show();
}
});
java.lang.IllegalStateException: Could not find method openDataPicker(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.textfield.TextInputEditText with id 'txt_from_user1'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:5368)
This error because it can't find the method openDataPicker(View) in the activity class (even if you already adding it to the fragment class).
Using android:onClick attribute in fragments is not exactly the same as in activities; weather you use it in activity or in fragment, it expects to see the method openDataPicker() only in the activity class.
Check here to see how to use android:onClick attribute in the fragment, or you can normally use the myButton.setOnClickListener() programmatically.
UPDATE:
So can you tell me according to the code, what I want to change in the code clearly
You can use setOnClickListener() in the fragment.
TextInputEditText editTextFrom = requireView().findViewById(R.id.txt_from_user1);
editTextFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPickerDialog_from.show();
}
});
TextInputEditText editTextTo = requireView().findViewById(R.id.txt_to_user1);
editTextTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPickerDialog_to.show();
}
});
And then remove the onClick attributes from the XML:
android:onClick="openDatePicker_to"
android:onClick="openDataPicker_from"

onClick method not working in android studio

I made a side navigation drawer and it works fine but whenever I click any option in navigation drawer nothing happens.It's like it is not taking any input. Onclicking any option I want to redirect user to a new activity but unfortunately it doesn't happens.
XML code is as follows
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Java code is as follows
public void ClickTournament_info(View view){
redirectActivity(this,TournamentInfo.class);
}
public static void redirectActivity(Activity activity,Class aClass) {
//Initialize intent
Intent intent = new Intent(activity,aClass);
//set flag
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//start activity
activity.startActivity(intent);
}
I think you need to use the onNavigationItemSelected method when you want to handle click events on the navigation drawer.
Learn more: https://developer.android.com/reference/com/google/android/material/navigation/NavigationView.OnNavigationItemSelectedListener#onNavigationItemSelected(android.view.MenuItem)
Firstly, try to always create an Onclicklistener instead of adding an onclick attribute in xml.
In your xml, add an ID attribute to your linear layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearlayout"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Now in your classfile inside the Oncreate Method,
LinearLayout LinearLayout = (LinearLayout )findViewById(R.id.linearlayout);
LinearLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
redirectActivity(this,TournamentInfo.class);
}
});
You already have an onClick method. start navigating from that method only.
Try like this,

Moving buttons with animation and changing their position afterwards

I am learning Java and Android SDK. I want to create a simple application that is swapping 2 buttons so the left one is moving to the place of right one and v.v. with simple animation. I have tried the ObjectAnimator because I have read that it is moving the views objects permanently. But it's not :-( The objects stays there I mean the left one on the right and v.v. but their getLeft(), getTop() values are the same, and after next animations starts the objects are returning to the start position immediately. I have read that the ObjectAnimator needs some additional function to work properly but in the documentation there is no example :-( I have tried to add the setTranslationX function but it hasn't worked. Could somebody provide me with some simple example of how to do this?
http://developer.android.com/guide/topics/graphics/prop-animation.html#object-animator
"The object property that you are animating must have a setter function (in camel case) in the form of set(). Because the ObjectAnimator automatically updates the property during animation, it must be able to access the property with this setter method. For example, if the property name is foo, you need to have a setFoo() method. If this setter method does not exist, you have three options:
Add the setter method to the class if you have the rights to do so.
Use a wrapper class that you have rights to change and have that wrapper receive the value with a valid setter method and forward it to the original object.
Use ValueAnimator instead."
Thanks in advance.
try this code:
public class ActivityStartup extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("hello");
setContentView(R.layout.main);
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.SLIDING_WINDOW);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setBehindOffset(100);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
View view = G.layoutInflater.inflate(R.layout.menu, null);
view.findViewById(R.id.layout_crop).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(G.context, "Crop Clicked", Toast.LENGTH_SHORT).show();
}
});
view.findViewById(R.id.img_logo).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://example.com"));
startActivity(browserIntent);
}
});
menu.setMenu(view);
}
}
public class G extends Application {
public static LayoutInflater layoutInflater;
public static Context context;
#Override
public void onCreate() {
super.onCreate();
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
context = getApplicationContext();
}
}
main.xml is:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
menu.xml is:
<ImageView
android:id="#+id/img_logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#drawable/hlogo" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:background="#00ff00"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:id="#+id/layout_crop"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_crop" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Crop"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_day"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_day" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Day"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_delete"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_delete" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="#000000" />
</LinearLayout>

Button in simple ListView onClick

So I have simple listview with a list item that contains a textview, and two imageviews.
I want both of the imageviews to act as buttons. Unfortunately, I can't even get one of them to work. The list view loads but then the app crashes when either image is touched. Here is the xml for the listitem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_card">
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#color/Black"
android:id="#+id/name"
android:textSize="20sp"
android:padding="16dp">
</TextView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:gravity="right">
<ImageView
android:layout_width="40dp"
android:layout_height="fill_parent"
android:id="#+id/email"
android:clickable="true"
android:src="#drawable/ic_action_email"
android:layout_margin="8dp"/>
<View
android:layout_width="2dp"
android:layout_height="match_parent"
android:background="#color/LightGrey" />
<ImageView
android:layout_width="40dp"
android:layout_height="fill_parent"
android:id="#+id/internet"
android:clickable="true"
android:layout_margin="8dp"
android:src="#drawable/ic_action_web_site" />
</LinearLayout>
</LinearLayout>
Here is the layout with the listview:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvDepartments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="8dp"
android:padding="8dp"
android:smoothScrollbar="true"
android:scrollbarStyle="insideOverlay"
android:listSelector="#color/Navy"/>
</LinearLayout>
Here is the related java code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.staff_layout);
staffmemberlist = (ListView)findViewById(R.id.lvDepartments);
ArrayAdapter<String> arrayAdapter =new ArrayAdapter<String> (getApplicationContext(),R.layout.emailbrowsingcard,R.id.name, d);
staffmemberlist.setAdapter(arrayAdapter);
mailbutton=(ImageView)findViewById(R.id.email);
mailbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"This line would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
}
this isnt going to work because the ImageView is in the item list so you should consider doing..
mailButton = (ImageView) row.findViewById(R.id.email);
where row is the item list. remember the ImageView isn't in staff_layout, it is in your item_layout.
to make it works you need to move this block:
mailbutton=(ImageView)findViewById(R.id.email);
mailbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"This line would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
to the getView() in your adapter class. and let the View get findViewById or have an instance of the item_layout view in order to reach the buttons.
you should use a custom adapter for that and in custom adapter use findViewById for finding imageviews and setting listener
this is a good tutorial: http://www.vogella.com/articles/AndroidListView/article.html

onClick on an imageview within a listview within a dialog

I can't seem to get an onClick event on an imageview from a class that extends Fragment. What am i doing wrong here? I'm relatively new to developing for android..
Currently, this code gives me a null pointer exception - when i add the onClickListener code
Here is my code:
ImageView mImageView = (ImageView) v.findViewById(R.id.option_icon);
mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
these icons are placed in a listview which is placed on a Dialog:
Dialog's list view and button:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="#+id/preset_list_view"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="#string/ok"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/image"/>
</LinearLayout>
items within the list view (imageview and textview):
<?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="match_parent" >
<ImageView
android:id="#+id/option_icon"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/option_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/image"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="20dp" />
</RelativeLayout>
It must be that the ImageView you're trying to find it outside the scope of whatever v refers to.
If the image view is inside a list view then you should add the onClickListener from within the adapter
The imageView that you are trying to find is not accessible from v. If the imageView is in the main layout then use findViewById without using v else first inflate the view and then use view.findViewById.

Categories

Resources