[英]Adding fragments to activity
First of all, I read everything here. 首先,我在这里阅读了所有内容。 https://developer.android.com/guide/components/fragments.html
https://developer.android.com/guide/components/fragments.html
I have one activity and I want to divide the screen horizontally and add 2 fragments. 我有一个活动,我想水平分割屏幕并添加2个片段。 I know how to add fragments on XML but I don't want that.
我知道如何在XML上添加片段,但我不想要那样。 I want to add them on Java.
我想在Java上添加它们。
So the problem is FragmentManager doesnt work unless my activity extends Fragment. 所以问题是除非我的活动扩展了Fragment,否则FragmentManager无法正常工作。 Should I do that on the activity or should I add fragment transaction methods on one of the fragments?
我应该在活动上执行此操作,还是应该在其中一个片段上添加片段事务方法?
If I extend my activity to Fragment, does it also become a fragment? 如果我将活动扩展到“片段”,它还会变成片段吗?
If I put the fragmentmanager and fragmenttransaction on one of the fragments how can I make the connection with activity? 如果我将fragmentmanager和fragmenttransaction放在一个片段上,该如何与活动建立连接?
this is the activity which I want my fragments displayed on 这是我希望片段显示的活动
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ConversionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversion);
NumpadFragment fragment = new NumpadFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.numpad_layout,fragment);
fragmentTransaction.commit();
}
}
and this is one of the fragments 这是碎片之一
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class NumpadFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_numpad,container,false);
}
}
Some suggestions: 一些建议:
fragmentTransaction.replace
(unless you need your fragments to be added to stack) fragmentTransaction.replace
(除非您需要将片段添加到堆栈中) newInstance()
method instead and create new fragment instance by calling that methrod. newInstance()
方法,并通过调用该方法来创建新的片段实例。 Also, implement interaction between your fragment and activity. getSupportFragmentManager
(because your fragment is android.support.v4.app.Fragment
) getSupportFragmentManager
(因为您的片段是android.support.v4.app.Fragment
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.