我的片段初始化按钮,我可以在调试器中看到它。 当我从在其布局中具有片段的活动调用方法setButtonText时,该按钮变为null。我看过互联网,但到目前为止我没有找到任何解决方案
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");
}
答案 0 :(得分:0)
FragmentTransaction不是实时执行的,你必须调用boolean result = fragmentTransaction.executePendingTransactions();在更新按钮之前。另外,为什么不更新片段中的按钮?