Java Android:TextView.setText()的结果被片段覆盖
我对使用片段有点陌生,在片段中设置TextView的文本时遇到了问题Java Android:TextView.setText()的结果被片段覆盖,java,android,android-fragments,textview,Java,Android,Android Fragments,Textview,我对使用片段有点陌生,在片段中设置TextView的文本时遇到了问题 void setTimerValue(int value){ this.timerValue = value; } 现在,我有一个单一的活动,有一组常见的六个按钮,还有两个片段,它们以线性布局显示。我能够使用按钮成功替换LinearLayout中的片段。然而,我注意到在这两个片段中有一些与更改TextView相关的奇怪行为 我在fragments类中有一个名为setTimer()的方法,它试图更改TextView中的
void setTimerValue(int value){
this.timerValue = value;
}
现在,我有一个单一的活动,有一组常见的六个按钮,还有两个片段,它们以线性布局显示。我能够使用按钮成功替换LinearLayout中的片段。然而,我注意到在这两个片段中有一些与更改TextView相关的奇怪行为
我在fragments类中有一个名为setTimer()的方法,它试图更改TextView中的文本。奇怪的是,这种方法很成功。但是,一秒钟后,文本将恢复为片段的layout.xml文件(一个空白字符串)中包含的TextView中的默认文本
我已经尝试在我replace
LinearLayout中的片段之前和之后调用setTimer()方法,结果都是一样的。如何更改此TextView的内容而不在片刻后将其覆盖?谢谢大家!
MainActivity.java的onCreate()
方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FocusFragment initialFragment = new FocusFragment();
initialFragment.setFragmentType( Constants.FRAGMENT_WORK );
initialFragment.setTimer( 25 );
getFragmentManager().beginTransaction()
.add( R.id.linearLayout_fragmentHolder, initialFragment, "fragment_work" )
.commit();
}
}
FocusFragment.java:
public class FocusFragment extends Fragment {
int fragment_type;
static TextView timer;
final String TAG = "FocusFragment";
public FocusFragment() {
}
public void setFragmentType( int fragment_type ) {
this.fragment_type = fragment_type;
}
public int getFragmentType() {
return this.fragment_type;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
if ( getFragmentType() == Constants.FRAGMENT_WORK ) {
rootView = inflater.inflate( R.layout.fragment_work, container, false );
} else {
rootView = inflater.inflate( R.layout.fragment_break, container, false );
}
timer = ( TextView ) rootView.findViewById( R.id.textView_timer );
return rootView;
}
public boolean setTimer( int timerValue ) {
if ( timer != null ) {
if ( timerValue < 10 ) {
timer.setText( "0" + timerValue + ":00" );
} else {
timer.setText( timerValue + ":00" );
}
Log.d( TAG, "Timer text set successfully." );
return true;
}
Log.w( TAG, "WARNING: setTimer() couldn't find the timer TextView!" );
return false;
}
}
问题是在调用
setTimer()
之后调用片段的OnCreateView()
方法
解决这个问题的一个简单方法是在创建片段时首先调用fragment.setTimerValue(value)
void setTimerValue(int value){
this.timerValue = value;
}
然后在OnCreateView()方法的末尾执行以下操作:
OnCreateView(){
...
setTimer(timerValue);
return rootView;
}
太棒了。完全有道理。非常感谢你的帮助!