Home > Software engineering >  How to open an activity from a fragment using imagebutton?
How to open an activity from a fragment using imagebutton?

Time:04-08

I have a Navigation drawer that has four different fragments. On the Home Fragment Dashboard, I have eight different image buttons that I want to open a new activity I.E. when you click the Image Button TM's I want it to open the TM's activity. I'm using kotlin as well.

I've watched numerous videos and forums on YouTube and google and none have seemed to work for what I'm doing.

// Dashboard.kt is where I have my ImageButtons, where I want each button to open a new activity.
package com.example.militarymainenance

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment


class Dashboard : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }
}

// fragment_dashboard.xml is where I have my ImageButtons, where I want each button to open a new activity.

 <?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Dashboard">

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



        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="140dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="32dp"
            android:layout_marginRight="20dp">


            <ImageView
                android:id="@ id/txtdashboard"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/dashboard3"
                android:textAlignment="center"
                android:textColor="#FFF" />


        </RelativeLayout>

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:rowCount="3"
            android:columnCount="2"
            android:alignmentMode="alignMargins">


            <androidx.cardview.widget.CardView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:cardBackgroundColor="@color/material_on_surface_stroke"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardElevation="6dp"
                app:cardCornerRadius="12dp"
                android:layout_margin="12dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:padding="16dp"
                    android:gravity="center">

                    <ImageButton
                        android:id="@ id/card1"
                        android:src="@drawable/folder3"
                        android:scaleType="centerCrop"
                        android:layout_width="130dp"
                        android:layout_height="130dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:textColor="@color/white"
                        android:text="@string/tm_s"/>


                </LinearLayout>

            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardBackgroundColor="@color/material_on_surface_stroke"
                app:cardElevation="6dp"
                app:cardCornerRadius="12dp"
                android:layout_margin="12dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:padding="16dp"
                    android:gravity="center">

                    <ImageButton
                        android:id="@ id/card2"
                        android:src="@drawable/circuit3"
                        android:scaleType="centerCrop"
                        android:layout_width="130dp"
                        android:layout_height="130dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:textColor="@color/white"
                        android:text="@string/schematics"/>


                </LinearLayout>

            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardBackgroundColor="@color/material_on_surface_stroke"
                app:cardElevation="6dp"
                app:cardCornerRadius="12dp"
                android:layout_margin="12dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:padding="16dp"
                    android:gravity="center">

                    <ImageButton
                        android:id="@ id/card3"
                        android:src="@drawable/parts3"
                        android:scaleType="centerCrop"
                        android:layout_width="130dp"
                        android:layout_height="130dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:textColor="@color/white"
                        android:text="@string/parts_cheat_sheet"/>


                </LinearLayout>

            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_columnWeight="1"
                android:layout_rowWeight="1"
                app:cardBackgroundColor="@color/material_on_surface_stroke"
                app:cardElevation="6dp"
                app:cardCornerRadius="12dp"
                android:layout_margin="12dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:padding="16dp"
                    android:gravity="center">

                    <ImageButton
                        android:id="@ id/card4"
                        android:src="@drawable/load3"
                        android:scaleType="centerCrop"
                        android:layout_width="130dp"
                        android:layout_height="130dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:textColor="@color/white"
                        android:text="@string/generator_load_wiring"/>


                </LinearLayout>

            </androidx.cardview.widget.CardView>

        </GridLayout>

    </LinearLayout>

</androidx.core.widget.NestedScrollView>

// MainActivity.kt which controls my navigation drawer.

package com.example.militarymainenance

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.google.android.material.navigation.NavigationView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*

class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close)
        toggle.isDrawerIndicatorEnabled = true
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        nav_menu.setNavigationItemSelectedListener(this)

        setToolbarTitle("Dashboard")
        changeFragment(Dashboard())


    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        drawerLayout.closeDrawer(GravityCompat.START)


        when(item.itemId){
            R.id.dashboard -> {
                setToolbarTitle("Dashboard")
                changeFragment(Dashboard())
            }

            R.id.equipment_tracker -> {
                setToolbarTitle("Equipment Tracker")
                changeFragment(Equipment_tracker())
            }

            R.id.service_tracker -> {
                setToolbarTitle("Service Tracker")
                changeFragment(Service_tracker())
            }

            R.id.faults_tracker -> {
                setToolbarTitle("Faults Tracker")
                changeFragment(Faults_tracker())
            }

            R.id.share -> {
                setToolbarTitle("Service Tracker")
                changeFragment(Service_tracker())
            }

            R.id.rate_us -> {
                setToolbarTitle("Faults Tracker")
                changeFragment(Faults_tracker())
            }
        }
        return true
    }

    fun setToolbarTitle(title:String){
        supportActionBar?.title = title
    }

    fun changeFragment(frag:Fragment){
        val fragment = supportFragmentManager.beginTransaction()
        fragment.replace(R.id.fragment_container,frag).commit()
    }



}

// activity_main.xml which controls my navigation bar

    <?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#515050"
    tools:context=".MainActivity">

    <include layout="@layout/content_main" />

    <com.google.android.material.navigation.NavigationView
        android:id="@ id/nav_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/navigation_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

CodePudding user response:

You should create ImageButton view in your xml file, then bind onClickListener to it and call startActivity when onClick triggers.

just an example to understand:

public class TabFragment1 extends Fragment {

ImageButton imageButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
    imageButton = (ImageButton)view.findViewById(R.id.imageButton);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(getActivity(),NewActivity.class);
        }
    });
    return view;}
  • Related