如何在Android的Fragment类中使用Activity代码? [英] How to use Activity code into Fragment class in Android?

查看:99
本文介绍了如何在Android的Fragment类中使用Activity代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动"类代码,我想复制到片段"类中,但不知道片段结构,有人可以帮助我做到这一点吗?下面是我的两节课:

MainActivity.java

 公共类MainActivity扩展了Activity {private String [] application = {"ABC","DEF","GHI","HIJ"};专用String []设备= {"ABC","DEF","GHI","HIJ"};私有RadioGroup radioGroup1;私有RadioGroup radioGroup2;私有RadioButton btn;私有RadioButton btn2;私有字符串text1;私有字符串text2;RadioButton button1;RadioButton button2;按钮全选;@Override公共无效onCreate(捆绑保存的InstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);checkButtonClick();drawRadiobuttons();}私人void checkButtonClick(){按钮myButton =(按钮)findViewById(R.id.findSelected);myButton.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){StringBuffer responseText = new StringBuffer();responseText.append(");//获取选定的单选按钮如果(radioGroup1.getCheckedRadioButtonId()!= -1){text1 = btn.getText().toString();Log.d("Button","Text 1:" + text1);}如果(radioGroup2.getCheckedRadioButtonId()!= -1){text2 = btn2.getText().toString();Log.d("Button","Text 2:" + text2);}Toast.makeText(getApplicationContext(),数据发布:应用程序:"+ text1 +"\ nDEVICE:" + text2,Toast.LENGTH_LONG).show();}});}私人void drawRadiobuttons(){radioGroup1 =(RadioGroup)findViewById(R.id.radio1);radioGroup2 =(RadioGroup)findViewById(R.id.radio2);ViewGroup hourButtonLayout =(ViewGroup)findViewById(R.id.radio1);for(int i = 0; i< application.length; i ++){button1 =新的RadioButton(this);button1.setId(i);button1.setText(application [i]);hourButtonLayout.addView(button1);radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){public void onCheckedChanged(RadioGroup mRadioGroup2,int CheckedId2){for(int i = 0; i< mRadioGroup2.getChildCount(); i ++){btn =(RadioButton)mRadioGroup2.getChildAt(i);int = mRadioGroup2.getId();System.out.println(t);如果(btn.getId()== checkedId2){text1 = btn.getText().toString();Toast.makeText(getApplicationContext(),您选择了:" + text1,Toast.LENGTH_SHORT).show();返回;}}}});}ViewGroup hourButtonLayout2 =(ViewGroup)findViewById(R.id.radio2);for(int i = 0; i< device.length; i ++){button2 =新的RadioButton(this);button2.setId(i);button2.setText(device [i]);hourButtonLayout2.addView(button2);radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){public void onCheckedChanged(RadioGroup mRadioGroup,int CheckedId){for(int i = 0; i< mRadioGroup.getChildCount(); i ++){btn2 =(RadioButton)mRadioGroup.getChildAt(i);int = mRadioGroup.getId();System.out.println(t);如果(btn2.getId()== checkedId){text2 = btn2.getText().toString();Toast.makeText(getApplicationContext(),您选择了:" + text2,Toast.LENGTH_SHORT).show();返回;}}}});}}} 

我想添加到"ImageFragment"代码中的同一运行活动"代码

ImageFragment.java

 公共类ImageFragment扩展Fragment {int fragVal;private String [] application = {"ABC","DEF","GHI","HIJ"};专用String []设备= {"ABC","DEF","GHI","HIJ"};私有RadioGroup radioGroup1;私有RadioGroup radioGroup2;私有RadioButton btn;私有RadioButton btn2;私有字符串text1;私有字符串text2;RadioButton button1;RadioButton button2;按钮全选;上下文此上下文;静态ImageFragment init(int val){ImageFragment truitonFrag = new ImageFragment();//提供val输入作为参数.Bundle args = new Bundle();args.putInt("val",val);truitonFrag.setArguments(args);返回truitonFrag;}@Override公共无效onCreate(捆绑保存的InstanceState){super.onCreate(savedInstanceState);fragVal = getArguments()!= null吗?getArguments().getInt("val"):1;}@Override公共视图onCreateView(LayoutInflater充气器,ViewGroup容器,捆绑保存的实例状态){thiscontext = container.getContext();视图layoutView = inflater.inflate(R.layout.activity_main,container,false);按钮myButton =(按钮)layoutView.findViewById(R.id.findSelected);myButton.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){StringBuffer responseText = new StringBuffer();responseText.append(");//获取选定的单选按钮如果(radioGroup1.getCheckedRadioButtonId()!= -1){text1 = btn.getText().toString();Log.d("Button","Text 1:" + text1);}如果(radioGroup2.getCheckedRadioButtonId()!= -1){text2 = btn2.getText().toString();Log.d("Button","Text 2:" + text2);}Toast.makeText(在这个背景下,数据过帐:APPLICATION:"+ text1 +"\ nDEVICE:" + text2,Toast.LENGTH_LONG).show();}});//绘制单选按钮radioGroup1 =(RadioGroup)layoutView.findViewById(R.id.radio1);radioGroup2 =(RadioGroup)layoutView.findViewById(R.id.radio2);ViewGroup hourButtonLayout =(ViewGroup)layoutView.findViewById(R.id.radio1);for(int i = 0; i< application.length; i ++){button1 =新的RadioButton(this);button1.setId(i);button1.setText(application [i]);hourButtonLayout.addView(button1);radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){public void onCheckedChanged(RadioGroup mRadioGroup2,int CheckedId2){for(int i = 0; i< mRadioGroup2.getChildCount(); i ++){btn =(RadioButton)mRadioGroup2.getChildAt(i);int = mRadioGroup2.getId();System.out.println(t);如果(btn.getId()== checkedId2){text1 = btn.getText().toString();Toast.makeText(thiscontext,您选择了:" + text1,Toast.LENGTH_SHORT).show();返回;}}}});}ViewGroup hourButtonLayout2 =(ViewGroup)layoutView.findViewById(R.id.radio2);for(int i = 0; i< device.length; i ++){button2 =新的RadioButton(this);button2.setId(i);button2.setText(device [i]);hourButtonLayout2.addView(button2);radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){public void onCheckedChanged(RadioGroup mRadioGroup,int CheckedId){for(int i = 0; i< mRadioGroup.getChildCount(); i ++){btn2 =(RadioButton)mRadioGroup.getChildAt(i);int = mRadioGroup.getId();System.out.println(t);如果(btn2.getId()== checkedId){text2 = btn2.getText().toString();Toast.makeText(thiscontext,您选择了:" + text2,Toast.LENGTH_SHORT).show();返回;}}}});}返回layoutView;}} 

解决方案

将您活动的 onCreate 代码复制到 Fragment onCreateView 中.

在片段中,您必须使用 layoutView 来获取视图实例.

喜欢下面的代码来获取按钮.

 按钮myButton =(按钮)findViewById(R.id.findSelected); 

将被转换为

 按钮myButton =(Button)layoutView.findViewById(R.id.findSelected); 

您可以将layoutView声明为类变量,而不是onCreateView中的局部变量,以使其在整个片段中均可访问.

  View layoutView;//使它可访问@Override公共视图onCreateView(LayoutInflater充气器,ViewGroup容器,捆绑保存的实例状态){layoutView = inflater.inflate(R.layout.activity_main,container,false); 

并且不要忘记从 onCreateView 上返回 layoutView 实例.

以上建议是基础知识,现在针对特定要求/问题发布问题,以获取更多有用的答案.

编辑,而不是,请使用 getActivity()来获取上下文实例.

就像 button1 = new RadioButton(this)中一样

button1 = new RadioButton(** getActivity()**);

上述原因是,在活动 this 中为您提供了上下文实例,因为Activity是Context的子类,但是在片段 this 中,您无法获得相同的访问权限,因此您需要使用getActivity()或getActivity().getBaseContext()来在需要时获取上下文实例.

I have a "Activity" class code which I want to copy into "Fragment" class but unaware of Fragment structure, can someone help me to do that? Below are my two classes :

MainActivity.java

public class MainActivity extends Activity {

    private String[] application = { "ABC", "DEF", "GHI", "HIJ" };                     
    private String[] device = { "ABC", "DEF", "GHI", "HIJ" }; 
    private RadioGroup radioGroup1;
    private RadioGroup radioGroup2;
    private RadioButton btn;
    private RadioButton btn2;
    private String text1;
    private String text2;
    RadioButton button1;
    RadioButton button2;
    Button selectall;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkButtonClick();
        drawRadiobuttons();

    }

    private void checkButtonClick() {

        Button myButton = (Button) findViewById(R.id.findSelected);
        myButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                StringBuffer responseText = new StringBuffer();
                responseText.append("");

                // Get selected radiobuttons
                if (radioGroup1.getCheckedRadioButtonId() != -1) {
                    text1 = btn.getText().toString();
                    Log.d("Button", "Text 1 : " + text1);
                }

                if (radioGroup2.getCheckedRadioButtonId() != -1) {
                    text2 = btn2.getText().toString();
                    Log.d("Button", "Text 2 : " + text2);
                }


                Toast.makeText(
                        getApplicationContext(),
                        "Data Posting : APPLICATION : "
                                + text1 + " \nDEVICE : " + text2,
                        Toast.LENGTH_LONG).show();


            }
        });

    }

    private void drawRadiobuttons(){

        radioGroup1 = (RadioGroup) findViewById(R.id.radio1);
        radioGroup2 = (RadioGroup) findViewById(R.id.radio2);

        ViewGroup hourButtonLayout = (ViewGroup) findViewById(R.id.radio1);
        for (int i = 0; i < application.length; i++) {
            button1 = new RadioButton(this);
            button1.setId(i);
            button1.setText(application[i]);
            hourButtonLayout.addView(button1);

            radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup mRadioGroup2,
                                int checkedId2) {
                            for (int i = 0; i < mRadioGroup2.getChildCount(); i++) {
                                btn = (RadioButton) mRadioGroup2.getChildAt(i);
                                int t = mRadioGroup2.getId();
                                System.out.println(t);

                                if (btn.getId() == checkedId2) {
                                    text1 = btn.getText().toString();
                                    Toast.makeText(getApplicationContext(),
                                            "You selected : " + text1,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                    });

        }

        ViewGroup hourButtonLayout2 = (ViewGroup) findViewById(R.id.radio2); 
        for (int i = 0; i < device.length; i++) {
            button2 = new RadioButton(this);
            button2.setId(i);
            button2.setText(device[i]);
            hourButtonLayout2.addView(button2);

            radioGroup2
                    .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup mRadioGroup,
                                int checkedId) {
                            for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
                                btn2 = (RadioButton) mRadioGroup.getChildAt(i);
                                int t = mRadioGroup.getId();
                                System.out.println(t);

                                if (btn2.getId() == checkedId) {
                                    text2 = btn2.getText().toString();
                                    Toast.makeText(getApplicationContext(),
                                            "You selected : " + text2,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                    });

        }

    }

}

The same running "Activity" code i want to add into "ImageFragment" code

ImageFragment.java

public class ImageFragment extends Fragment {
    int fragVal;
    private String[] application = { "ABC", "DEF", "GHI", "HIJ" };                     
    private String[] device = { "ABC", "DEF", "GHI", "HIJ" }; 
    private RadioGroup radioGroup1;
    private RadioGroup radioGroup2;
    private RadioButton btn;
    private RadioButton btn2;
    private String text1;
    private String text2;
    RadioButton button1;
    RadioButton button2;
    Button selectall;
    Context thiscontext;

    static ImageFragment init(int val) {
        ImageFragment truitonFrag = new ImageFragment();
        // Supply val input as an argument.
        Bundle args = new Bundle();
        args.putInt("val", val);
        truitonFrag.setArguments(args);
        return truitonFrag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        thiscontext = container.getContext();
        View layoutView = inflater.inflate(R.layout.activity_main, container, false);

        Button myButton = (Button) layoutView.findViewById(R.id.findSelected);
        myButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                StringBuffer responseText = new StringBuffer();
                responseText.append("");

                // Get selected radiobuttons
                if (radioGroup1.getCheckedRadioButtonId() != -1) {
                    text1 = btn.getText().toString();
                    Log.d("Button", "Text 1 : " + text1);
                }

                if (radioGroup2.getCheckedRadioButtonId() != -1) {
                    text2 = btn2.getText().toString();
                    Log.d("Button", "Text 2 : " + text2);
                }


                Toast.makeText(
                        thiscontext,
                        "Data Posting : APPLICATION : "
                                + text1 + " \nDEVICE : " + text2,
                        Toast.LENGTH_LONG).show();


            }
        });


        //Draw Radiobuttons

        radioGroup1 = (RadioGroup) layoutView.findViewById(R.id.radio1);
        radioGroup2 = (RadioGroup) layoutView.findViewById(R.id.radio2);

        ViewGroup hourButtonLayout = (ViewGroup) layoutView.findViewById(R.id.radio1);
        for (int i = 0; i < application.length; i++) {
            button1 = new RadioButton(this);
            button1.setId(i);
            button1.setText(application[i]);
            hourButtonLayout.addView(button1);

            radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup mRadioGroup2,
                                int checkedId2) {
                            for (int i = 0; i < mRadioGroup2.getChildCount(); i++) {
                                btn = (RadioButton) mRadioGroup2.getChildAt(i);
                                int t = mRadioGroup2.getId();
                                System.out.println(t);

                                if (btn.getId() == checkedId2) {
                                    text1 = btn.getText().toString();
                                    Toast.makeText(thiscontext,
                                            "You selected : " + text1,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                    });

        }

        ViewGroup hourButtonLayout2 = (ViewGroup) layoutView.findViewById(R.id.radio2); 
        for (int i = 0; i < device.length; i++) {
            button2 = new RadioButton(this);
            button2.setId(i);
            button2.setText(device[i]);
            hourButtonLayout2.addView(button2);

            radioGroup2
                    .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup mRadioGroup,
                                int checkedId) {
                            for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
                                btn2 = (RadioButton) mRadioGroup.getChildAt(i);
                                int t = mRadioGroup.getId();
                                System.out.println(t);

                                if (btn2.getId() == checkedId) {
                                    text2 = btn2.getText().toString();
                                    Toast.makeText(thiscontext,
                                            "You selected : " + text2,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                    });

        }



        return layoutView;
    }
}

解决方案

copy your activity's onCreate code into onCreateView of Fragment.

in fragment you have to use layoutView to get views instances.

like your below code to get button.

    Button myButton = (Button) findViewById(R.id.findSelected);

would be converted into

    Button myButton = (Button)layoutView.findViewById(R.id.findSelected);

you can declare layoutView as a class variable instead of local variable in onCreateView to make it accessible in whole fragment.

View layoutView; // making it accessible
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    layoutView = inflater.inflate(R.layout.activity_main, container, false);

and do not forget to return layoutView instance from onCreateView.

above suggestion are basics, now post question for specific requirement/issue, to get more helpful answer.

Edit instead of this use getActivity() to get context instance.

like in button1 = new RadioButton(this) you should use

button1 = new RadioButton(**getActivity()**);

reason for above is, in activity this gives you instance of context as Activity is sub class of Context, but in fragment this can not give you access of the same,hence you would need to use getActivity() or getActivity().getBaseContext() to get context instance where required.

这篇关于如何在Android的Fragment类中使用Activity代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆