如何通过按下按钮在第二个片段的TextView中设置Text [英] How to set a Text in the TextView of the second fragment by pushing on the button
问题描述
我在一个Android应用中有1个活动,其中包含2个片段. 在第一个片段上,我确实放了一个按钮(btnA). 在第二个上,我推了一个TextView(txtB).
I have 1 activity with 2 fragments in an Android app. On the first fragment, I did put a button (btnA). On the second I putt a TextView (txtB).
如何通过在第一个活动上按下按钮来在第二个片段的TextView中设置文本?
How can I set a Text in the TextView of the second fragment by pushing on the button on the first activity?
Thx,我是android应用程序开发的新手
Thx, I'm new to android app development
JoskXP
推荐答案
Following Android best practice described here.
这比Graeme的解决方案稍微冗长一些,但允许重复使用您的片段. (您可以在另一个屏幕中使用FragmentWithButton,并且该按钮可以执行其他操作)
This is slightly more verbose than the solution of Graeme, but allow reuse of your fragments. (You could use FragmentWithButton in another screen, and the button could do something different)
您有两个片段(FragmentWithButton
和FragmentWithText
)和一个活动(MyActivity
)
You have two Fragments (FragmentWithButton
and FragmentWithText
) and one activity (MyActivity
)
-
在
FragmentWithButton
中创建界面FragmentWithButtonHost
:
public class FragmentWithButton extends Fragment {
FragmentWithButtonHost host;
public interface FragmentWithButtonHost{
public void onMyButtonClicked(View v);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
host = (FragmentWithButtonHost) activity;
}
catch (ClassCastException e) {
// TODO Handle exception
}
}
/**
* Click handler for MyButton
*/
public void onMyButtonClick(View v) {
host.onMyButtonClicked(v);
}
}
在FragmentWithText
中创建 public 方法以设置活动中的文本:
Create a public method in FragmentWithText
to set the text from the activity:
public class FragmentWithText extends Fragment{
...
public void setText(String text) {
// Set text displayed on the fragment
}
}
确保您的活动实现了FragmentWithButtonHost
接口,并调用setText
方法:
Make sure your activity implements the FragmentWithButtonHost
interface, and call the setText
method:
public MyActivity implements FragmentWithButtonHost {
...
@Override
public void onMyButtonClicked(View v) {
getFragmentWithText().setText("TEST");
}
public FragmentWithText getFragmentWithText() {
// Helper method to get current instance of FragmentWithText,
// or create a new one if there isn't any
}
}
这篇关于如何通过按下按钮在第二个片段的TextView中设置Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!