简体   繁体   中英

How to call android:onClick on xml button under another xml listview using fragment?

I tried this method and inflate home.xml in my HomeFragment.java:

    public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.home, container, false);
        return root;
    }

    public void OnClickOnTransit(View v){
        final Button n = (Button) v;
        final String id = n.getTag().toString();

        AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1);
        arrayAdapter.add("Tag as On Transit");
        arrayAdapter.add("Cancel");


        builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strOption = arrayAdapter.getItem(which);
                if(strOption.equalsIgnoreCase("Tag as On Transit"))
                {
                    Tag_as_on_transit(id);
                }
                else if(strOption.equalsIgnoreCase("Cancel"))
                {
                    //confirmViewLeveling(emp_tag[1],emp_name.getText().toString());
                }
                else
                {

                }
            }
        });
        builderSingle.show();

    }

Here is my home.xml where i put my listview.

<ListView
    android:id="@+id/lv_customer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

And this is my nested_listview.xml where my button was placed.

<Button
    android:id="@+id/btn_ontransit"
    android:layout_width="40dip"
    android:layout_height="40dip"
    android:background = "@drawable/ic_local_shipping_orange_24dp"
    android:textColor="#ff4500"
    android:textStyle="bold"
    android:text=""
    android:textSize="25sp"
    android:onClick="OnClickOnTransit"/>

What i want is to call OnClickOnTransit from nested_listview.xml. Thanks in advance!

In that case your parentActivity must have this method

 public void OnClickOnTransit(View v){
}

However if you don't want that, You can implement like this in your fragment's onViewcreated method.

 Button btn_conferma = (Button) view.findViewById(R.id.btn_conferma);
       btn_conferma.setOnClickListener(new OnClickListener()
       {
                 @Override
                 public void onClick(View v)
                 {
                    // do something
                 } 
       }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM