java - 从Activity设置片段EditeText的文本
问题描述
如何从活动中设置片段的 EditText 的文本?
这是活动代码:
public class MainActivity extends AppCompatActivity
{
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Personal"); // set the Text for the first Tab
tabLayout.addTab(firstTab); // add the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Chat"); // set the Text for the second Tab
tabLayout.addTab(secondTab); // add the tab in the TabLayout
try {
Fragment fragment = null;
fragment = new FirstFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
try {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void connect(){
//set text of EditText of SecondFragment
}
}
我正在寻找解决此问题的方法:我想创建一个聊天客户端,为此我需要不时更新选项卡的 EditText 而无需切换到该选项卡。我还需要在切换选项卡时不会丢失该 EditText 的内容。
解决方案
只需在主要活动中创建一个变量,您可以从片段中更新该变量。由于活动的生命周期不会从一个片段更改到另一个片段,因此您可以从第二个片段获得相同的值。
我希望这有帮助。
推荐阅读
- sql - SQL For循环在列中查找空值,而不是空值
- linux - AMD Epyc (Zen 2) 禁用硬件预取 L2
- serial-port - 串行端口环回测试如何在内部/下面工作?
- java - 与 Beam 中的运行器依赖项冲突
- botframework - Microsoft Teams APP Studio - 在清单编辑器中找不到消息端点字段
- python - 如何使用 PuLP 编写迭代 LP 变量、obj 函数和约束?
- java - LibGDX 纹理在移动时闪烁 - 似乎没有什么可以解决它
- spring - 无法为某些 URL 禁用 Spring Security 过滤器链
- javascript - Typescript 模块 xyz 没有库 node_modules 的专家成员
- javascript - 以编程方式创建的 Vue 组件缺少在 Vue.prototype 上定义的全局属性