简体   繁体   English

Android如何从我的主要活动中调用Fragment

[英]Android How to call Fragment from my Main Activity

i am very new to android development. 我是android开发的新手。

in my case i have one main activity and one fragment created.Main activity as two buttons. 在我的情况下,我有一个主要活动和一个片段创建。主要活动为两个按钮。

when i click on button, my fragment should load .how can i achieve that? 当我点击按钮时,我的片段应该加载。我可以实现吗?

Mainactivity .XML 主动.XML

<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
    android:text="Fragment 2"
    android:id="@+id/fragment_button_2"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fragment 1"
    android:id="@+id/fragment_button_1"
    android:layout_above="@+id/fragment_button_2"
    android:layout_alignLeft="@+id/fragment_button_2"
    android:layout_alignStart="@+id/fragment_button_2"
    android:layout_marginBottom="33dp" />
</RelativeLayout>

Main activity .java 主要活动.java

package com.bentgeorge.fragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements    View.OnClickListener{
private Button fragment_btn_1;
private Button fragment_btn_2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fragment_btn_1 = (Button) findViewById(R.id.fragment_button_1);
    fragment_btn_2 = (Button) findViewById(R.id.fragment_button_2);


}

@Override
public void onClick(View v) {

Fragment1 frag = new Fragment1();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.mainlayout,frag,"Test Fragment");
transaction.commit();

}
}

fragment_fragment1.xml fragment_fragment1.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bentgeorge.fragment.Fragment1">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />

</FrameLayout>

Fragment1.java Fragment1.java

package com.bentgeorge.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
* A simple {@link Fragment} subclass.
*/
public class Fragment1 extends Fragment {


public Fragment1() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment1, container,  false);
}

}

Not done much codes as i am confused with internet available tutorials. 没有做太多的代码,因为我与互联网可用的教程混淆。

Please help me to fix this 请帮我解决这个问题

Thanks & Regards, 感谢和问候,

Update: 更新:

i have done some changes and my fragment is getting loaded now. 我做了一些更改,我的片段现在正在加载。 ut the buttons are still visible . 按钮仍然可见。 How can i hide the buttons 我该如何隐藏按钮

分段

Updated: Please change your MainActivity as like this: 更新:请更改您的MainActivity,如下所示:

  public class MainActivity extends AppCompatActivity  {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Fragment fragment = new MainFragment();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

        }
    }

Change your activity_main.xml as like this: 像这样更改您的activity_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"                
android:id="@+id/fragment_frame"            
android:layout_width="match_parent"
            android:layout_height="match_parent" />

Please create an xml fragment_main.xml: 请创建一个xml fragment_main.xml:

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"                
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
    <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
        android:text="Fragment 2"
        android:id="@+id/fragment_button_2"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment 1"
        android:id="@+id/fragment_button_1"
        android:layout_above="@+id/fragment_button_2"
        android:layout_alignLeft="@+id/fragment_button_2"
        android:layout_alignStart="@+id/fragment_button_2"
        android:layout_marginBottom="33dp" />
    </RelativeLayout>

Also create a fragment as MainFragment: 还要创建一个片段作为MainFragment:

public class MainFragment extends Fragment implements View.OnClickListener{
     private Button fragment_btn_1;
        private Button fragment_btn_2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        fragment_btn_1 = (Button) view.findViewById(R.id.fragment_button_1);
            fragment_btn_2 = (Button) view.findViewById(R.id.fragment_button_2);
            fragment_btn_1.setOnClickListener(this);
            fragment_btn_2.setOnClickListener(this);
        return view;
    }
@Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.fragment_button_1:
                    Fragment fragment1 = new Fragment1();
                    moveToFragment(fragment1);
                    break;
                case R.id.fragment_button_2:
                    Fragment fragment2 = new Fragment2();
                    moveToFragment(fragment2);
                    break;
            }
        }

        private void moveToFragment(Fragment fragment) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

        }
}

Hope this will helps you. 希望这会对你有所帮助。 If you had any queries, let me know. 如果您有任何疑问,请告诉我。

in you onClick() method - 你在onClick()方法 -

if(v.getId()==R.id.fragment_button_1){
getActivity().getSupportFragmentManager().beginTransaction()
                            .add(R.id.fragment_frame, new Fragment1(), "createPost").addToBackStack(null).commit();
              }

where R.id.fragment_frame - rootContainer Id rootView in MainActivity.java 其中R.id.fragment_frame - MainConctivity.java中的rootContainer Id rootView

you should use Framelayout for placing fragment in activity. 你应该使用Framelayout将片段放入活动中。

like below - activity_layout.xml - 如下所示 - activity_layout.xml -

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapplication.Activities.TestActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="40dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Button 1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/button1"
            android:layout_centerHorizontal="true"
            android:text="Button 1" />

    </LinearLayout>

</FrameLayout>

and your activity - MainActivity.java 和你的活动 - MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class TestActivity extends AppCompatActivity implements View.OnClickListener{

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

        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @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_test, 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);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button1){
            getSupportFragmentManager().beginTransaction().
                    replace(R.id.root_layout, new Fragment1()).commit();
        }
    }
}

btw your fragment looks good. 顺便说一句你的片段看起来不错。 hope it will help you. 希望它会对你有所帮助。

You can't call Fragments via Intent. 你不能通过Intent调用Fragments。 Fragment is a part of an FragmentActivity. 片段是FragmentActivity的一部分。

All in all Fragment is a content not container, so you need to create a FragmentActivity and add Fragment(Fragment1) in that, and then call on your onClick(), 总而言之,Fragment是一个内容而不是容器,所以你需要创建一个FragmentActivity并在其中添加Fragment(Fragment1),然后调用onClick(),

Intent intent = new Intent(MainActivity.this, SomeFragmentActivity.class);
startActivity(intent);

More info : here 更多信息: 这里

use getActivity() from the fragment to access activity functions. 使用片段中的getActivity()来访问活动函数。 If you want to access functions specific to your own activity class. 如果要访问特定于您自己的活动类的函数。 Cast the acticity object you get first before using it see example below 在使用之前首先演示您获得的acticity对象,请参阅下面的示例

MyActivityClass myActivity = (MyActivityClass) getActivity();

Create one more activity say ExampleFragmentActivity.class, and include fragment tag in ExampleFragmentActivity's layout within Framelayout. 再创建一个活动,例如ExampleFragmentActivity.class,并在Framelay格式中的ExampleFragmentActivity布局中包含片段标记。

public class ExampleFragmentActivity extends AppCompatActivity {

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

example_fragment_activity.xml(modified) example_fragment_activity.xml(修改)

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.bentgeorge.fragment.Fragment1">

            <fragment
                android:id="@+id/titles"
                class="com.bentgeorge.fragment.Fragment1"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    </FrameLayout>

In Onclick method of your MainAcitivity.class 在MainAcitivity.class的Onclick方法中

Intent intent = new Intent(MainAcitivity.this,ExampleFragmentActivity.class);

You can also include fragment dynamically using fragment manager. 您还可以使用片段管理器动态包含片段。

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.add(R.id.fragment_container, fragment1, "fragment");
fragmentTransaction.commit();
 FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
   HomeFragment regcomplainfragment = new HomeFragment();
   fragmenttransaction.replace(R.id.content_frame, regcomplainfragment).addToBackStack("HomeFragment");
   fragmenttransaction.commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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