【发布时间】:2021-10-16 06:09:40
【问题描述】:
我有一个显示来自 API 的数据的片段,但我不想在每次调用片段时都调用 apis.. 所以我从不同的类调用 api 并调用片段中的方法来更新 UI(textViews ) 但是 textViews 出现 null 异常,但那里的数据是 100%
如果我尝试硬编码 textView.setText("Hello") 它可以工作..
【问题讨论】:
标签: java android fragment settext
我有一个显示来自 API 的数据的片段,但我不想在每次调用片段时都调用 apis.. 所以我从不同的类调用 api 并调用片段中的方法来更新 UI(textViews ) 但是 textViews 出现 null 异常,但那里的数据是 100%
如果我尝试硬编码 textView.setText("Hello") 它可以工作..
【问题讨论】:
标签: java android fragment settext
片段的任务之一是改变用户界面!您必须更改活动或片段中的用户界面
您必须使用 interface 。你的服务器类:
public class server {
.
.
.
public void callServer(IServerResponse iResponse){
.
.
.
iResponse.onResponse(//your data such as List or string or json and etc);
}
public interface IServerResponse{
// use parameter type as you want like List or string ,etc..
void onResponse(String data);
}
}
您的片段或活动实现您的界面:
public class SomeFragment extends Fragment implements Server.IServerResponse{
....
@Override
public View onCreateView(...){
...
Server server=new Server();
server.callServer(this);
}
@Override
public void IServerResponse(String data){
textview.SetText(data);
}
}
【讨论】:
你应该在你的活动中创建一个 FrameLayout 并使用此代码:
FragmentA newFragment = new FragmentA ();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).commit();
然后设置你的文本
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
newFragment .setText(editValueName, lastStatus);
【讨论】:
如果它对您的期望输出有效,请尝试快速修复
在 textview 起源的类(你的活动)中使 Textview 静态化,例如public static TextView textview;
在片段中if(youractivity.textView!=null){ youractivity.textView.setText("your desire text"); }
【讨论】: