将数据从Dialog传递到android

时间:2017-02-02 16:54:47

标签: android android-fragments tags

我目前正在自己​​的牙科应用项目中工作,我想询问如何从自定义对话框中传递某些数据并显示或将其添加到目标片段?

感谢任何帮助。

这是自定义对话框截图:

enter image description here

CustomDialog.java

package com.bloxofcode.multipletabs;

import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.bloxofcode.multipletabs.Tab1;

public class CustomDialog extends Dialog implements
        View.OnClickListener {

    public Activity c;
    public CustomDialog d;
    public Button yes, no;

    ToggleButton btnGenderMale,btnGenderFemale;
    Button btnCancel, btnAccept;
    EditText eText;

    public CustomDialog(Activity a) {
        super(a);
        // TODO Auto-generated constructor stub
        this.c = a;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setBackgroundDrawableResource(android.R.drawable.dialog_holo_light_frame);
        }
        else{
            getWindow().setBackgroundDrawableResource(android.R.drawable.alert_light_frame);
        }

        setContentView(R.layout.activity_dialog);


        btnGenderFemale = (ToggleButton) findViewById(R.id.toggleButtonFemale);
        btnGenderMale = (ToggleButton) findViewById(R.id.toggleButtonMale);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnAccept = (Button) findViewById(R.id.btnAccept);
        eText = (EditText) findViewById(R.id.editText);

        btnGenderMale.setChecked(true);

        btnGenderMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonMale, boolean b) {
//                        Toast.makeText(getApplicationContext(),
//                                String.valueOf(buttonMale.isChecked()), Toast.LENGTH_SHORT).show();
                if(buttonMale.isChecked()){
                    btnGenderMale.setEnabled(false);
                    btnGenderFemale.setEnabled(true);
                    btnGenderFemale.setChecked(false);
                }else{

                }
            }
        });

        btnGenderFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonFemale, boolean b) {
//                        Toast.makeText(getApplicationContext(),
//                                String.valueOf(buttonFemale.isChecked()), Toast.LENGTH_SHORT).show();
                if(buttonFemale.isChecked()){
                    btnGenderMale.setEnabled(true);
                    btnGenderFemale.setEnabled(false);
                    btnGenderMale.setChecked(false);
                }else{

                }
            }
        });


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        btnAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"Sample",Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        dismiss();
    }
}

如何实现此预期结果:

enter image description here

Tab1.java

package com.bloxofcode.multipletabs;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;

import com.bloxofcode.multipletabs.database.DBOpenHelper;
import com.bloxofcode.multipletabs.database.NotesProvider;

/**
 * A simple {@link Fragment} subclass.
 */
public class Tab1 extends Fragment {
    private ImageButton imgButton;
    private CustomDialog customDialog;
    View v;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v =inflater.inflate(R.layout.tab_1,container,false);

        imgButton = (ImageButton) v.findViewById(R.id.imageButton);
        //Creating ImageButton

        imgButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // Toast.makeText(getActivity(),"Hello Image Button!",Toast.LENGTH_LONG).show();
                customDialog = new CustomDialog(getActivity());
                customDialog.show();
            }
        });

        press();
        return v;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void press() {
        insertNote("Juan Dela Cruz");

        Cursor cursor = getActivity().getContentResolver().query(NotesProvider.CONTENT_URI,
                DBOpenHelper.ALL_COLUMNS, null, null, null, null);
        String[] from = {DBOpenHelper.NOTE_TEXT};
        int[] to = {android.R.id.text1};
        CursorAdapter cursorAdapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_1,cursor,from,to,0);

        ListView list = (ListView) v.findViewById(android.R.id.list);
        list.setAdapter(cursorAdapter);
    }

    private void insertNote(String noteText) {
        ContentValues values = new ContentValues();
        values.put(DBOpenHelper.NOTE_TEXT,noteText);
        Uri noteUri =getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI,values);

        Log.d("MainActivity","Inserted note " + noteUri.getLastPathSegment());
    }


}

ViewPagerAdapter.java

package com.bloxofcode.multipletabs;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;


public class ViewPagerAdapter extends FragmentStatePagerAdapter{

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {

        if(position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;
        }
        else if(position == 1)
        {
            Tab2 tab2 = new Tab2();
            return tab2;
        }
        else             // As we are having 3 tabs if the position is now 0 it must be 1 so we are returning second tab
        {
            Tab3 tab3 = new Tab3();
            return tab3;
        }


    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}

TabsActivity.java

package com.bloxofcode.multipletabs;

import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class TabsActivity extends AppCompatActivity {

    // Declaring Your View and Variables
    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Patient","Appointment","Backup"};
    int Numboftabs =3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabs);


        // Creating The Toolbar and setting it as the Toolbar for the activity
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                //return ContextCompat.getColor(TabsActivity.this,R.color.tabsScrollColor);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return getResources().getColor(R.color.tabsScrollColor,TabsActivity.this.getTheme());
                }else {
                    return getResources().getColor(R.color.tabsScrollColor);
                }
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

6 个答案:

答案 0 :(得分:1)

如果你想保持松散耦合和结构化的东西,那么选择EventBus就可以了。要查看用法,请参阅此Answer

答案 1 :(得分:1)

您可以使用Interface完成此操作。

<强> YourInterface.java

public interface YourInterface{
    void yourMethod(int data);
}

在Dialog类中使用该接口:

public class CustomDialog extends Dialog implements
    View.OnClickListener {

    private YourInterface delegate;

    ....

    public CustomDialog(Activity a) {
        super(a);
        // TODO Auto-generated constructor stub
        this.c = a;
        delegate = (YourInterface) a;
    }

}

在包含片段实现接口的Activity中:

public class YourActivity extends AppCompatActivity implements YourInterface {

    ....

    @Override
    public void yourMethod(int data) {
        fragment.receiverMethod(data);
    }

}

<强> Tab1.java

public class Tab1 extends Fragment {

    public void receiverMethod(int data) {
        // do what you want with received data
    }
}

现在使用它只需调用delegate.yourMethod(data)将其传递给片段

答案 2 :(得分:0)

您可以在对话框中的onDismiss中使用广播接收器,如下所示

@Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (onDismissListener != null) {
            Intent intent = new Intent("DialogDismiss");
            LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);

            onDismissListener.onDismiss(dialog);
        }
    }

在您的片段中,您可以收到广播

//在你的片段中

BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
         //Work Here
        }
    };

//在OnCreate

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver,
                new IntentFilter("DialogDismiss"));

//的onDestroy

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);

答案 3 :(得分:0)

如果您从customDialog获得视图,则可以通过片段类中的view.findViewById()正常访问字段。

答案 4 :(得分:0)

将您的数据作为键值对放入萌芽,并将bundle设置为fragment的参数。 fragment.setArgument(束)

要在fragmen中获得捆绑,请致电 Bundle bundle = getArgument()并根据键从bundle中获取值。

答案 5 :(得分:0)

你可以通过在Dialog类中创建一个setter和getter方法来返回输入到EditText中的String,以返回一个String变量(例如=[Table]![NameCriteria]![Name] ),只要接受按钮是点击。

将getter和setter方法添加到Dialog类

editTextString

在“接受”按钮的单击侦听器中,添加以下代码行:

private void setEditTextString() { editTextString = eText.getText().toString() } public String getEditTextString() { return editTextString; }

然后,您需要做的就是返回在Fragment类的editText字段中输入的值,即调用Dialog类中的public方法返回字符串。

setEditTextString(eText.getText().toString());