我试图在几秒钟后更改片段的背景图像,但是仍然遇到问题!我使用片段是因为我使用了标签栏。该应用程序将正常运行直到2.5秒,这是更改背景的时间!并且我确定问题是由代码而不是应用引起的!
这是我的代码:
public class LogInFragment extends android.support.v4.app.Fragment {
LinearLayout login_layout;
public LogInFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
login_layout = (LinearLayout) getActivity().findViewById(R.id.linear1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
change();
}
}, 2500);
}
private void change()
{
Random random = new Random();
int image_change = random.nextInt(5 - 1) + 1;
switch (image_change)
{
case 1:
login_layout.setBackgroundResource(R.drawable.blue1);
break;
case 2:
login_layout.setBackgroundResource(R.drawable.yellow1);
break;
case 3:
login_layout.setBackgroundResource(R.drawable.red1);
break;
default:
login_layout.setBackgroundResource(R.drawable.green1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_log_in, container, false);
}
}
如果有人可以帮助我,我将很高兴!
答案 0 :(得分:0)
删除login_layout =(LinearLayout)getActivity()。findViewById(R.id.linear1);从oncreate。因为在片段中我们必须使用inflate,所以请改为在oncreateview中找到该视图。在oncreateview中尝试:View rootView = inflater.inflate(R.layout.fragment_log_in,container,false); login_layout =(LinearLayout)rootView.findViewById(R.id.linear1);返回rootView
由@ user3576118解答...!