【问题标题】:Passing a data from Dialog to Fragment in android在android中将数据从Dialog传递到Fragment
【发布时间】:2017-02-02 16:54:46
【问题描述】:

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

感谢任何帮助。

这是自定义对话框截图:

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();
    }
}

如何实现这个预期结果:

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);
    }

}

【问题讨论】:

  • 我的回答有帮助吗?
  • 您好先生,我使用了界面...尚未尝试事件总线...但会尝试...谢谢
  • 好的,接口也是一个选项。如果对我的回答没有帮助,请标记我的答案。

标签: android android-fragments tags


【解决方案1】:

如果您想保持松散耦合和结构化,一个不错的替代方案是选择 EventBus 。要查看用法,请参阅此Answer

【讨论】:

    【解决方案2】:

    您可以使用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) 将其传递给片段

    【讨论】:

    • 您好,先生,我对使用界面有点困惑,我需要为此包含 onAttach 方法吗?
    • 您好!是的,您需要覆盖 onAttach 方法,因为它是获取可以转换到界面的上下文/活动的最简单(如果不是唯一)方法。
    • 您好,先生,我是这里的新手,正在连接所有代码。但是我在代码中使用了 viewpageadapter 我试图创建一个接口并将它实现到我的 TabsActivity 但我总是得到一个错误。
    • @iamcoder 你有什么错误,你不清楚答案的哪一部分?
    • 我认为这个链接可以帮助我对界面有所了解..stackoverflow.com/questions/4279787/…
    【解决方案3】:

    您可以在 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);
            }
        }
    

    在你的片段中你可以接收广播

    // 在您的 Fragment 中执行以下操作

    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);
    

    【讨论】:

      【解决方案4】:

      如果您从customDialog 获取视图,您可以在片段类中使用view.findViewById() 正常访问字段。

      【讨论】:

        【解决方案5】:

        将您的数据作为键值对放入 budle 并将 bundle 设置为片段的参数。 fragment.setArgument(bundle)

        要在片段中获取捆绑包,请调用 Bundle bundle = getArgument() 并根据 key 从 bundle 中获取值。

        【讨论】:

          【解决方案6】:

          您可以通过在 Dialog 类中创建一个 setter 和 getter 方法来返回输入到 EditText 中的 String 以返回一个 String 变量(例如 editTextString),您可以在单击接受按钮时为其分配一个值。

          将您的 getter 和 setter 方法添加到 Dialog 类

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

          在接受按钮的点击侦听器中添加以下代码行:

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

          那么,返回在 Fragment 类的 editText 字段中输入的值所需要做的就是调用 Dialog 类中的公共方法来返回字符串。

          dialogClass.getEditTextValue()

          【讨论】:

          • 在你的 setEditTextString() 函数中,你没有参数。但是在您的接受按钮中,您使用了它并传递了 eText.getText().toString() 这是不正确的。同样通过这样做,假设片段获得了传递的值,它将返回 null 因为在片段中它已经获取数据,即使还没有点击事件
          猜你喜欢
          • 1970-01-01
          • 2018-02-13
          • 1970-01-01
          • 1970-01-01
          • 2021-05-11
          • 2021-05-12
          • 1970-01-01
          • 1970-01-01
          • 2021-02-19
          相关资源
          最近更新 更多