This question already has answers here:
Android Fragment onClick button Method
(7 answers)
Closed 2 years ago.
I am very new to Android Studio. What I want is simple: I press on a button and something should happen.
So I have a button in my fragment that looks in XML like this:
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:text="#string/hello"
android:onClick="doSumth"
/>
My code in GeneralFragment.java looks like this:
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ch.yourclick.kitt.R;
/**
* A simple {#link Fragment} subclass.
* Use the {#link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_general, container, false);
}
public void doSumth() {
System.out.println("Hello");
}
}
My problem is that I get the error:
java.lang.IllegalStateException: Could not find method doSumth(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.App
What am I doing wrong?
You have to add a View argument to a function. It has to look like this:
public void doSumth(View view)
{
System.out.println("Hello");
}
Responding to Click Events - Android docs
Also You can make it in code like this:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1 = (Button) findViewById(R.id.b1);
bt1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
System.out.println("Hello");
}
});
}
}
You need add a View parameter in your method. When you use android:onClick in XML , the method need a view like parameter.
The this code:
public void doSumth(View view) {
System.out.println("Hello");
}
Related
I want to know how to code inside a fragment.java file. Firstly, I am a beginner in coding. I have created a Bottomnavigationview with three navigation buttons in the bottomnaviation bar and I have created Fragment activity for each of the navigation buttons. One of the navigation options in the bottom navigation bar is 'more' and I have added a button with the id "btn_Logoff". when I click the button I want it to go the activity_login.xml or LoginActivity.java. I dont know what is the code for that and where to add the code in the default fragment java file so here is what is written on the fragment file by default:
filename is MoreFragment.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
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.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MoreFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MoreFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MoreFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public MoreFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MoreFragment.
*/
// TODO: Rename and change types and number of parameters
public static MoreFragment newInstance(String param1, String param2) {
MoreFragment fragment = new MoreFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_more, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Notification Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Ive been having a lot of trial and errors and still no resolution. Any help appreciated. Thank you.
Can you explain this part?
when I click the button I want it to go the activity_login.xml or LoginActivity.java.
Do you want to execute something in activity after click on button in fragment, am I right?
You can do it for some ways. Easiest is set listener that listening when you clicking on the button.
Create interface:
public interface OnNavigationButtonClickListener {
void onMoreClick();
}
Create listener variable in fragment:
private OnNavigationButtonClickListener navigationListener;
and setter for it:
public void setNavigationListener(OnNavigationButtonClickListener listener) {
this.navigationListener = listener;
}
3.Notify your listeners in fragment on more button click:
onMoreButton.setOnClickListener(new OnClickListener {
navigationListener.onMoreClick();
});
4. Then set listener in your activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment.setNavigationListener(new OnNavigationButtonClickListener() {
#Override
public void onMoreClick() {
// you clicked 'more' button in fragment
// do what you want
}
});
Assuming thay you already identified btn_Logoff with the findViewById and everything
all you need to do is add a onclickListener that launchs the activity you want, your code for the clicklistener will look similar to this
Button btn_Logoff;
your class{
btn_Logoff = (Button) findViewById(R.id.IdOfYourBtnInTheXmlFile);
btn_Logoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
I know this question is asked often but none of the accepted solutions have worked for me. (reference solution)
I'm getting the classic "Wrong 2nd argument type" error when I try to launch a Preference Menu fragment from within one of my otherfragments.
Unforunately, even after doing what the accepted answer in that question suggests (calling FragmentManager fragmentManager = getSupportFragmentManager() and importing android.support.v4.app.FragmentManager; I still see the "Wrong 2nd argument type" bug when I call .replace().
A quick overview: my MainActivity.java opens a fragment viewpager (MenuPager.java), from which I try to launch another fragment (FragmentSettingsMenu.java) when a button is clicked within FragmentTrackRecordMenu.java (a child fragment of MenuPager.java).
My code is below. I try to launch the settings menu fragment when the menu button (within FragmentTrackRecord) is clicked but I can't get around the aforementioned compiler error. How can I display my PreferencesFragment successfully from this onClick?
MainActivity.java
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
public static ViewPager menuPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
menuPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pageAdapter = new MenuPagerAdapter(getSupportFragmentManager());
menuPager.setAdapter(pageAdapter);
...
}
}
MenuPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MenuPagerAdapter extends FragmentPagerAdapter {
public MenuPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new FragmentNeckDisplayMenu();
case 1:
return new FragmentCapoMenu();
case 2:
return new FragmentTrackRecordMenu();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
FragmentTrackRecordMenu.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public class FragmentTrackRecordMenu extends Fragment {
private Button menuIcon;
public FragmentTrackRecordMenu(){ } //default constructor
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.menu_fragment_recorder, container, false);
menuIcon = (Button) v.findViewById(R.id.menuIcon);
menuIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //open popup window
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(android.R.id.content, new FragmentSettingsMenu()) //COMPILER ERROR
.commit();
}
});
}
}
FragmentSettingsMenu.java
public class FragmentSettingsMenu extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from the XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
getSupportFragmentManager() returns the fragment manager of android.support.v4.app.FragmentManager and your FragmentSettingMenu.java is of android.app.Fragment. That's why "Wrong 2nd argument type" error because they are incompatible.
your FragmentManager is of v4 type and FragmentSettingsMenu is not a v4 type.Hence it does not allow.Try the below line in activity.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
.try this link here
it may give you some help.
So today I created tab view bar and fragments and added some image buttons to one of the fragments.
When I add android:onClick="name"on the button code and write Intent in .java file, it gives me force close error when I click on that button.
Here's my code:
fragment.xml
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnProgramiPL5x5"
android:minHeight="80dp"
android:background="#mipmap/btn_programi_pl_5x5"
android:onClick="ProgramiPowerlifting5x5"/>
fragment.java
package hr.app.liftme.liftmehr;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
/**
* A simple {#link Fragment} subclass.
*/
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_powerlifting, container, false);
}
ProgramiPowerlifting5x5.java
package hr.app.liftme.liftmehr;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_programi_powerlifting5x5);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
}
}
Error i get is this:
01-26 23:00:44.766 14491-14491/hr.app.liftme.liftmehr E/AndroidRuntime: FATAL EXCEPTION: main
Process: hr.app.liftme.liftmehr, PID: 14491
java.lang.IllegalStateException: Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'btnProgramiPL5x5'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
I don't know what is the problem, when I link two activities I use this, name.class, but that didn't worked in this case so i used getActivity and it still does not work.
I would really appreciate help!
Thanks!
The problem here is:
Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context
The onClick attribute refers to the parent Context (as parent Activity) so the fragment's method is not triggered and not handled by this attribute.
You have to handle the click in the Activity:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
...
// change the method's name to avoid confusion with constuctor
public void ProgramiPowerLifting(View view){
Intent intent = new Intent(this, ProgramiPowerlifting5x5.class);
startActivity(intent);
}
}
Or trigger the same method into your fragment:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
private ProgramPowerFragment fragment;
...
public void ProgramiPowerLifting(View view){
fragment.ProgramiPowerLifting(view);
}
}
This great answer uses a callback interface which, personally, I'd suggest. Or you can easily forget the onClick xml attribute and do it dynamically with setOnClickListener().
So, let's try the easy way:
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// store the layout in a view variable
View v = inflater.inflate(R.layout.fragment_powerlifting, container, false);
// use this view ("v") to retrieve elements on the layout by its id
ImageButton imgButton = (ImageButton) v.findViewById(R.id.btnProgramiPL5x5);
// set a listener to the button
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open a new activity when onClick is triggered
Intent intent = new Intent(getActivity(), ProgramiPowerLiftingActivity.class);
startActivity(intent);
}
}
// return the inflated view to display it
return v;
}
}
I'm essentially a new Android Studio developer and currently I am attempting to switch between 3 tabs for my program. Unfortunately, the program forces a close when I try to open things up. I'm not entirely sure where the problem lies since I declared an instance of the classes in regards to the tab.
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Main extends Activity implements ActionBar.TabListener {
Fragment FragmentTab1 = new Tab1();
Fragment FragmentTab2 = new Tab2();
Fragment FragmentTab3 = new Tab3();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auth_port, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Fragment fragment = null;
if (position == 0)
{
fragment = FragmentTab1;
}
if (position == 1)
{
fragment = FragmentTab2;
}
if (position == 2)
{
fragment = FragmentTab3;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return 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;
}
}
Tab1 (The Other 2 Tabs are the same)
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Charge#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class Tab1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1
*/
// TODO: Rename and change types and number of parameters
public static Charge newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Tab1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab1, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
I've looked on other websites for help on this, mostly they cover programs that are obsolete or don't cover the question completely, I have nothing else to turn to so any help on this problem I'd appreciate it.
Edit: I've learned it has to do with creating a .newinstance of the class but how this gets accomplished I haven't quite grasped yet.
Logcat output. Only included error portion
10-29 21:04:04.599 9452-9452/com.example.main
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.authpayx.authportbeta04, PID: 9452
java.lang.ClassCastException: com.example.main.main#42d45398 must implement
OnFragmentInteractionListener
at com.example.main.Tab1.onAttach(Tab1.java:84)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)
at android.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:785)
at android.app.Fragment.setUserVisibleHint(Fragment.java:997)
at android.support.v13.app.FragmentCompatICSMR1.setUserVisibleHint(FragmentCompatICSMR1.java:23)
at android.support.v13.app.FragmentCompat$ICSMR1FragmentCompatImpl.setUserVisibleHint(FragmentCompat.java:48)
at android.support.v13.app.FragmentCompat.setUserVisibleHint(FragmentCompat.java:76)
at android.support.v13.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:134)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:412)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2548)
at android.view.View.measure(View.java:17478)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2262)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1391)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1590)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6585)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
at android.view.Choreographer.doCallbacks(Choreographer.java:603)
at android.view.Choreographer.doFrame(Choreographer.java:573)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
You must implement OnFragmentInteractionListener inside your main activity.
change
public class Main extends Activity implements ActionBar.TabListener
to
public class Main extends Activity implements ActionBar.TabListener, OnFragmentInteractionListener
Then make sure your implement
public void onFragmentInteraction(Uri uri);
inside your main activity.
A little info on the new instance method. This is a common practice not a special method you are implementing. You can call it anything that you want but the idea is that new instance method takes your parameters and adds them to a bundle. when android destroys your fragment it gets recreated using its default constructor which does not have your data.
The solution is to use a new instance method and put your data in a bundle because when android recreates your fragment its bundle sticks around.
The only time you would not care about new instance is when you are not passing anything into your fragment.
It seems that this issue related to your Tab1 Fragment class. Also it seems that you created this Fragment class by android studio auto generated blank Fragment class.
For fixing this issue you can change codes of auto generated Fragment classes like Tab1 with code like below.
package com.example.android.actionbarcompat.styled;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by taher on 1/7/15.
*/
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.main_view, container, false);
}
}
If you want to use your Tab1 fragment class please not that below comment from your Fragment Class.
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
I had the same problem, and in my case,
delete
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
these code, problem solved
Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code:
package karim.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
}
and i got this error :
Description Resource Path Location Type
The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem
can you please tell me whats wrong ????
Please Be specific !!
My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, #Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6.
Change the compiler version, or remove the #Override annotation on the onClick method.
You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs:
http://developer.android.com/guide/topics/ui/ui-events.html
public class TestActivity extends Activity{
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
or in your case
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
if(v==b1)
{
//button logic
}
}
As an extension to "JB Nizet" answer:
The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition.
<Button android:text="Click Me!"
android:onClick="doSomething"
/>
In your java-code:
public void doSomething(View v){
// Do stuff here
}
This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6
Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.