0

I am new to android and is in need for some little help.I have a xml layout called fragment_home.xml which contains some images.I want to redirect the user to another page(fragment_about_sl.xml) when the user clicks on an image.Please tell me how to do that and where to place the codes.

fragment_home.xml(layout with the images)

<LinearLayout
android:id="@+id/home"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.homeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal">

        <ImageView
            android:id="@+id/aboutslbtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:src="@drawable/aboutsl"
            />
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:layout_marginBottom="10dp"
            android:src="@drawable/toplandmarks"
            />

    </LinearLayout>
</ScrollView>
</LinearLayout>

fragment_about_sl.xml(the layout that should be redirected once image is clicked)

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/aboutslscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.aboutSLFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="250dp" />

        <LinearLayout
            android:id="@+id/SliderDots"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/viewPager"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" />


    </RelativeLayout>


</LinearLayout>

</ScrollView>

I also added the java file if its necessary.

homeFragment.java(java file for fragment_home.xml)

public class homeFragment extends Fragment {


public homeFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_home, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("Destinations");
}

}

aboutSLFragment.java(java file for fragment_about_sl.xml)

public class aboutSLFragment extends Fragment{

ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
TextView aboutsltext;
Button readmorebtn;

public aboutSLFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_about_sl, container, false);
    viewPager = (ViewPager) rootView .findViewById(R.id.viewPager);

    sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());

    viewPager.setAdapter(viewPagerAdapter);

    dotscount = viewPagerAdapter.getCount();
    dots = new ImageView[dotscount];

    for(int i = 0; i < dotscount; i++){

        dots[i] = new ImageView(getContext());
        dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(8, 0, 8, 0);

        sliderDotspanel.addView(dots[i], params);

    }

    dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            for(int i = 0; i< dotscount; i++){
                dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));
            }

            dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    aboutsltext=(TextView)rootView.findViewById(R.id.aboutsltext);
    readmorebtn=(Button)rootView.findViewById(R.id.readmorebtn);
    readmorebtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (readmorebtn.getText().toString().equalsIgnoreCase("Read More"))
            {
                aboutsltext.setMaxLines(Integer.MAX_VALUE);//your TextView
                readmorebtn.setText("Read Less");
            }
            else
            {
                aboutsltext.setMaxLines(3);//your TextView
                readmorebtn.setText("Read More");
            }
        }
    });

    // Inflate the layout for this fragment
    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("About Sri Lanka");
}

code added to change the fragment

 rootView.findViewById(R.id.aboutslbtn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Fragment fragment = new aboutSLFragment();
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.home, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }
    });

logcat

 30388-30388/com.example.sloid.destinations E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.sloid.destinations, PID: 30388
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sloid.destinations/com.example.sloid.destinations.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5951)
                                                                                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:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                at com.example.sloid.destinations.navigationdrawerfragments.homeFragment.onCreateView(homeFragment.java:30)
                                                                                at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                                                                                at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                                                                                at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                                                                                at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                                                                                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
                                                                                at android.app.Activity.performStart(Activity.java:6329)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767) 
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:177) 
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449) 
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                at android.os.Looper.loop(Looper.java:145) 
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5951) 
                                                                                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:1399) 
C. Chan
  • 57
  • 5
  • Possible duplicate of [How to move from one fragment to another fragment on click of a ImageView in Android?](https://stackoverflow.com/questions/23212162/how-to-move-from-one-fragment-to-another-fragment-on-click-of-a-imageview-in-and) – Vidhi Dave Feb 20 '18 at 12:26
  • try this answer : https://stackoverflow.com/a/23212245/8089770 – Vidhi Dave Feb 20 '18 at 12:26
  • I've added a piece of code but there is an error I can't resolve.The error is that as soon as I add aboutSLFragment to Fragment fragment new aboutSLFragment() it gives and error called unreachable statement making all thee lines in this code underlined in red.Please tell me what should I do? – C. Chan Feb 21 '18 at 08:02
  • make sure import of Fragment used to replace the fragment and in aboutFragment both are support v4 fragments – Vidhi Dave Feb 21 '18 at 08:12
  • I found the error, it was caused by adding the following code after the return inflater.inflate(R.layout.fragment_home, container, false);.Its solved now, but now another error arised, can you check that, i've addedd the logcat – C. Chan Feb 21 '18 at 08:38
  • And also as shown in this main method of the code in this link(http://abhiandroid.com/ui/fragment) there is something called a .I don't have that in my code.What is that used for and is that the problem causing the error in my case – C. Chan Feb 21 '18 at 08:44
  • Frame layout is the layout in which your all fragment will inflate. It is like a container. you can change things in this container by this code. – Vidhi Dave Feb 21 '18 at 08:47
  • Here in the code in replace you are giving the id is the contaner's id in which you are changing the fragment – Vidhi Dave Feb 21 '18 at 08:58
  • I didn't get you man.Can you explain me that clearly.I changed my fragment chanaging code too(have a look ) but as the logcat says the error is caused by the following line of code.Can you say whats the problem rootView.findViewById(R.id.aboutslbtn).setOnClickListener(new View.OnClickListener() – C. Chan Feb 21 '18 at 09:19
  • Is aboutslbtn is the id of layout which you are inflating? check the id may be it can not find the id. and first find the reference and then apply on click – Vidhi Dave Feb 21 '18 at 09:25
  • And check is home id is of container which holds fragment1 and now will replace to fragment2 – Vidhi Dave Feb 21 '18 at 09:27
  • Hello vishva, aboutslbtn is the id of the image in which if pressed redirects to another fragment and home is the id of the layout which holds that.(see the first code set)Why is the way I implemented it is wrong, please could you correct that. To explain you clearly I have a fragment layout called fragment_home.xml which has an image with id called aboutslbtn, which on click should redirect to fragment_about_sl.xml. Is the way I implemented the code is wrong,if so can you correct that – C. Chan Feb 21 '18 at 09:40
  • Let me try. Every fragment has one activity which contains them right? So there should be one Activity which contains homeFragment. Now in that activity where this content is should be a frame layout and that is the container. which will have an id. Ok now once again let me clear Activity is having container which holds homeFragment. and now in homeFragment imageview click you will redirect to aboutSLFragment. this will replace in activity container from homeFragment. That replacement code is perfect just that id need to be from activity(Container). – Vidhi Dave Feb 21 '18 at 09:45
  • That is all i know about fragment :D. Hope you got my point or can try tutorial for fragments. See Container is a box in the activity and you have put a paper in the box your homeFragment. now you want to take that paper and put a new one in the same box. then you will need one box and it's id. in which you will perform all this.right now you are taking id of first paper not box :( – Vidhi Dave Feb 21 '18 at 09:47
  • try this https://www.javacodegeeks.com/2013/06/android-fragment-transaction-fragmentmanager-and-backstack.html – Vidhi Dave Feb 21 '18 at 09:54
  • Bit of trail and error solved the case.Thanks Vishva for your utmost support given to me – C. Chan Feb 21 '18 at 10:34
  • Errors solved by me and accepting answer of other one :( :( – Vidhi Dave Feb 21 '18 at 10:35
  • Of course you solved it,But you answered in the comment section, and how to accept comments, there is no correct symbol in comment section, that's why I thanked you specifically – C. Chan Feb 21 '18 at 10:38
  • :D thank for that. I have posted the answer – Vidhi Dave Feb 21 '18 at 10:40

4 Answers4

2

Just add ids to those images and handle onclick events inside your fragment. You can find the image view using findViewById(R.id.'yourId');

And the onClick listener set: view.setOnClickListener(...);

Maksym V.
  • 2,877
  • 17
  • 27
0

You are new in android right, first of all you need to check Fragment detail

As you question you need to replace or add fragment as @Vishva Dave said

Follow this link

private void loadFragment(Fragment fragment) {

// create a FragmentManager
FragmentManager fm = getFragmentManager();

// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();

// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);

fragmentTransaction.commit(); // save the changes
}
Adil
  • 812
  • 1
  • 9
  • 29
  • I've added a piece of code but there is an error I can't resolve.The error is that as soon as I add aboutSLFragment to Fragment fragment new aboutSLFragment() it gives and error called unreachable statement making all thee lines in this code underlined in red.Please tell me what should I do? – C. Chan Feb 21 '18 at 08:03
0

First you need to add android:id="@+id/imageId" to the <ImageView ... in the xml, then in your homefragment add this code:

public class homeFragment extends Fragment {
View rootView;

public homeFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
// Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_home, container, false);
    rootView.findViewById(R.id.imageId).setOnClickListener(new OnClickListener(){
        // go to the other fragment using fragmentTransaction
    });
    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments 
different titles
    getActivity().setTitle("Destinations");
    }

}
Khalid Taha
  • 3,183
  • 5
  • 27
  • 43
0

As per My comment

Reference : Fragment replace

 Fragment fragment = new aboutSLFragment();
 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 fragmentTransaction.replace(R.id.home, fragment);
 fragmentTransaction.addToBackStack(null);
 fragmentTransaction.commit();

Tutorial : https://www.javacodegeeks.com/2013/06/android-fragment-transaction-fragmentmanager-and-backstack.html

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55