【问题标题】:Android Fragment forgets buttonAndroid Fragment忘记按钮
【发布时间】:2014-11-19 12:53:03
【问题描述】:

我的片段初始化按钮,我可以在调试器中看到它。 当我从布局中包含片段的活动中调用 setButtonText 方法时,按钮变为空。我在网上查过,但到目前为止我没有找到任何解决方案

public class PrepareTrainingFragment extends Fragment
{
private Button button;
private TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.preparetrainingfragment, container, false);
    button=(Button) v.findViewById(R.id.ptfragmentbtn);
    Log.w("button init","button init");
    return v;
}

public void setButtonText(String text)
{
    button.setText(text);
}

在封装片段的类中:

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
//  getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); //hide navigation bar temporarily


    driverFragment=new PrepareTrainingFragment();


    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = 
    fragmentManager.beginTransaction();

    fragmentTransaction.replace(android.R.id.content, driverFragment);

    driverFragment.setButtonText("hello");


}       

【问题讨论】:

    标签: android button null fragment


    【解决方案1】:

    FragmentTransaction 不是实时执行的,你必须调用 boolean result = fragmentTransaction.executePendingTransactions();在更新您的按钮之前。另外,为什么不更新 Fragment 中的按钮?

    【讨论】:

    • 因为有时需要从其他类中更改按钮上的文本
    • executePendingTransactions 解决问题了吗?
    • 不,不是,顺便说一句,它不是 fragmentManager.executePendingTransactions() 吗?我只想使用片段来重用其中的代码...
    • 您的 Activity 是否具有与 Fragment 通信的接口?
    • 尝试传递消息。一个警告:这将使您的片段依赖于活动,这不是推荐的设计。我让我的片段以这种方式相互交谈。
    猜你喜欢
    • 2023-03-05
    • 2018-05-30
    • 2017-05-13
    • 2014-02-07
    • 2011-12-20
    • 2017-11-07
    • 2013-07-22
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多