【问题标题】:Android How to call Fragment from my Main ActivityAndroid 如何从我的主要活动中调用片段
【发布时间】:2016-06-06 08:43:09
【问题描述】:

我对 android 开发非常陌生。

在我的情况下,我创建了一个主要活动和一个片段。主要活动作为两个按钮。

当我点击按钮时,我的片段应该加载。我怎样才能做到这一点?

主要活动 .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>

主要活动.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

<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

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

}

没有做太多代码,因为我对互联网上可用的教程感到困惑。

请帮我解决这个问题

感谢和问候,

更新:

我做了一些更改,现在我的片段正在加载。 ut 按钮仍然可见。如何隐藏按钮

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

    更新: 请像这样更改您的 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();
    
            }
        }
    

    像这样改变你的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" />
    

    请创建一个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>
    

    同时创建一个片段作为 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();
    
            }
    }
    

    希望这会对您有所帮助。如果您有任何疑问,请告诉我。

    【讨论】:

    【解决方案2】:

    在你的 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 - MainActivity.java 中的 rootContainer Id rootView

    您应该使用 Framelayout 将片段放置在活动中。

    如下 - 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>
    

    和你的活动 - 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();
            }
        }
    }
    

    顺便说一句,您的片段看起来不错。希望对你有帮助。

    【讨论】:

    • 您好,感谢您的回复。实际上我对点击事件做了一些改变,现在片段正在显示。但问题是按钮在我的主屏幕上仍然可见。如何在加载片段时隐藏按钮
    • 在提供代码时,我无法解析“getActivity()”和“addToBackStack”
    • 在片段的 rootView 中设置一些背景,因为您可能在活动之上添加片段。或者你也可以使用 - replace.(R.id.fragment_frame, new Fragment1())。
    • 我尝试过使用“transaction.replace(R.id.mainlayout,frag,"Test Fragment");"还。一样的显示。我为活动添加了背景颜色#fff,没有区​​别,但在我的主要活动中出现了一个边距白色区域
    • 在片段的 rootView 中添加背景 - schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="white_color" 工具:context="com.bentgeorge.fragment.Fragment1">
    【解决方案3】:

    你不能通过 Intent 调用 Fragments。 Fragment 是 FragmentActivity 的一部分。

    总而言之,Fragment 是一个内容而不是容器,所以你需要创建一个 FragmentActivity 并在其中添加 Fragment(Fragment1),然后调用你的 onClick(),

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

    更多信息:here

    【讨论】:

      【解决方案4】:

      使用片段中的 getActivity() 来访问活动功能。如果您想访问特定于您自己的活动类的功能。在使用它之前先投射你首先获得的活动对象,请参见下面的示例

      MyActivityClass myActivity = (MyActivityClass) getActivity();
      

      【讨论】:

        【解决方案5】:

        再创建一个活动,比如 ExampleFragmentActivity.class,并在 Framelayout 中的 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(修改)

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

        在 MainAcitivity.class 的 Onclick 方法中

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

        您还可以使用片段管理器动态包含片段。

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment1 fragment1 = new Fragment1();
        fragmentTransaction.add(R.id.fragment_container, fragment1, "fragment");
        fragmentTransaction.commit();
        

        【讨论】:

          【解决方案6】:
           FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
             HomeFragment regcomplainfragment = new HomeFragment();
             fragmenttransaction.replace(R.id.content_frame, regcomplainfragment).addToBackStack("HomeFragment");
             fragmenttransaction.commit();
          

          【讨论】:

            猜你喜欢
            • 2022-01-25
            • 2016-06-15
            • 1970-01-01
            • 1970-01-01
            • 2016-08-17
            • 1970-01-01
            • 2021-10-13
            • 2021-03-04
            • 2014-09-01
            相关资源
            最近更新 更多