Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set onclick listener for a button in a fragment in android

My app contains a form as shown in the following image:

register screenshot

When I click on menu options button, the drawer opens as shown in the following image: select screenshot

I want the drawer to open when the button select location is pressed.

My codes are

RegisterBlood.java

 ...
public class RegisterBlood extends Activity implements OnItemClickListener {
    DrawerLayout dLayout, dLayout2;
    ListView dList, dList2;
    ArrayAdapter<String> adapter, adapter2;
    String[] state_data2;
    String city = "", state = "";
    Button location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectlocation);
        Bundle args = new Bundle();

        Fragment detail = new RegisterBloodFragment();
        detail.setArguments(args);
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, detail)
                .commit();

    ...
        dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        dList = (ListView) findViewById(R.id.left_drawer);
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, state_data);
        dList.setAdapter(adapter);
        dList.setSelector(android.R.color.holo_blue_dark);
        // dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        dList.setOnItemClickListener(this);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent e) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            // your action...
            if (!dLayout.isDrawerOpen(dList)) {
                dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
                dList = (ListView) findViewById(R.id.left_drawer);
                adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1, state_data2);
                dList.setAdapter(adapter);
                dLayout.openDrawer(dList);
                dList.setOnItemClickListener(this);

            }

            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // your action...
            if (dLayout.isDrawerOpen(dList)) {
                dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            return true;
        }

        return super.onKeyDown(keyCode, e);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View v, final int position,
            long id) {
        // TODO Auto-generated method stub

        ...

        dLayout2 = (DrawerLayout) findViewById(R.id.drawer_layout);
        dList2 = (ListView) findViewById(R.id.left_drawer);
        adapter2 = new ArrayAdapter<String>(RegisterBlood.this,
                android.R.layout.simple_list_item_1, city_data);
        dList2.setAdapter(adapter2);
        dList2.setSelector(android.R.color.holo_blue_dark);
        dLayout2.openDrawer(dList2);
        dLayout2.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
        dList2.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position2,
                    long id) {
                dLayout2.closeDrawers();
                state = state_data2[position];
                city = city_data[position2];

                Bundle args = new Bundle();
                args.putString("Menu", city_data[position2] + " ("
                        + state_data2[position] + ")");
                Fragment detail = new RegisterBloodFragment();
                detail.setArguments(args);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame, detail).commit();

            }
        });

    }}

RegisterBloodFragment.java

...

public class RegisterBloodFragment extends Fragment implements OnClickListener {
    Button location;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
        View view = inflater.inflate(R.layout.registerblood, container, false);
        String menu = getArguments().getString("Menu");
        location= (Button) view.findViewById(R.id.etlocation);
        location.setText(menu);
        //Context c=getActivity();
        //location.setOnClickListener(c.getApplicationContext().set);
        return view;
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast.makeText(getActivity(),
                "Yes",
                Toast.LENGTH_SHORT).show();

    }

}

registerblood.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/silver"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="10dp"
    android:paddingLeft="40dp"
    android:paddingRight="40dp"
    android:paddingTop="10dp" >

    <EditText
        android:id="@+id/bregetName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:hint="Name" />

    <EditText
        android:id="@+id/bregetBloodGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:hint="Blood Group" />

        <Button
            android:id="@+id/etlocation"
            style="@android:style/Widget.EditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="14dp"
            android:ems="10"
            android:hint="select location" >
        </Button>

    <Button
        android:id="@+id/bregbtnSignUp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="10sp"
        android:layout_marginTop="10sp"
        android:background="@drawable/button"
        android:shadowColor="#A8A8A8"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="5"
        android:text="Submit"
        android:textColor="#FFFFFF"
        android:textSize="24sp" />

</LinearLayout>

selectlocation.xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >


</FrameLayout>

 <ListView android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#fff"/>

My question is:

How to add onclicklistener for select location button in RegisterBlood.java or call onClickListener which is in RegisterBlood.java from RegisterBloodFragment.java ?

Please help me out.

like image 315
Abhishek E H Avatar asked Jan 15 '15 13:01

Abhishek E H


People also ask

How to add onClick to fragment?

Solution: You have to use the onClick="."" Transfer entry from the layout/fragment. xml page to the codebehind page in java/project/fragment_page. java and connect it to an onClicklistener on a resource.

What does setOnClickListener do in Android?

OnClickListener and wires the listener to the button using setOnClickListener(View. OnClickListener) . As a result, the system executes the code you write in onClick(View) after the user presses the button. The system executes the code in onClick on the main thread.

How do I start an intent from a fragment?

If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .

How do you make toast in a fragment?

This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.


3 Answers

First of all remember to implements the OnClickListener interface:

public class YourClassName extends Fragment implements View.OnClickListener

public Button button;

Then, inside the method OnCreateView, inflate the button and set the listener to it, like this:

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

    button = (Button) inflater.inflate(R.layout.registerblood, container, false).findViewById(R.id.your_button_id);
    button.setOnClickListener(this);

}

Then @Override the function onClick and do whatever you gotta do:

@Override
public void onClick(View v) {
    //YOUR CODE HERE
}

EDIT If you're simply looking for a FocusListener (in that case your question needs an update) set the listener on your onCreateView method:

your_edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus) {
        Toast.makeText(getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
        // OPEN THE DRAWER HERE
    } else {
         Toast.makeText(getApplicationContext(), "lost the focus", Toast.LENGTH_LONG).show();
    }
}

or you can implement that listener to your class.

like image 158
Stefano Munarini Avatar answered Sep 17 '22 17:09

Stefano Munarini


Since the button is a part of the fragment's layout, set the listener there:

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
    View view = inflater.inflate(R.layout.registerblood, container, false);
    String menu = getArguments().getString("Menu");
    location = (Button) view.findViewById(R.id.etlocation);
    location.setText(menu);
    location.setOnClickListener(this);

    return view;
}

@Override
public void onClick(View v) {
    RegisterBlood activity = (RegisterBlood) getActivity();
    // Now you can contact your activity through activity e.g.:
    activity.onKeyDown(KeyEvent.KEYCODE_MENU, null);
}
like image 34
Simas Avatar answered Sep 20 '22 17:09

Simas


u need to inflate fragment like this for button click

  View view = inflater.inflate(R.layout.fragment_blank3,
            container, false);
   Button bt1=(Button)view.findViewbyId(R.id.buttton);
   bt1.setOnclick...
   //then return in on create view.
    return view;

// this works good, thankyou

like image 38
Syed Danish Haider Avatar answered Sep 20 '22 17:09

Syed Danish Haider