仪表板片段

时间:2018-06-10 12:21:43

标签: java android

您好我正在尝试创建一个Dashboard片段但是,我缺少一些代码行,需要您的帮助!基本上,当单击每个项目时,它会打开一个新活动。

代码:

public class DashboardFragment extends Fragment {

RelativeLayout rellay_timeline, rellay_friends, rellay_chat, rellay_music,
        rellay_gallery, rellay_map, rellay_weather, rellay_settings;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_dashboard, container, false);


    //SOMETHING NEEDS TO GO HERE*****


    rellay_timeline = view.findViewById(R.id.rellay_timeline);
    rellay_friends = view.findViewById(R.id.rellay_friends);
    rellay_chat = view.findViewById(R.id.rellay_chat);


    rellay_timeline.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), Activity_Timeline.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    });

    rellay_friends.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), Activity_Friends.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    });
    rellay_chat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), Activity_Chat.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    });
    }

我得到的错误是说我需要返回一些东西但是如果我只是返回视图那么它就不起作用了。我知道在onCreateView之后,一些代码需要去那里但是很难弄清楚它是什么,因为我从Activity教程中获取代码并尝试将其实现为Fragment。

1 个答案:

答案 0 :(得分:0)

首先,您必须在return view方法的末尾onCreateView(),但您还需要使用onCreateView()调用父super.onCreateView(inflater, container, savedInstanceState)方法:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
    // Initialize your stuff here
    setupUI(view);
    return view;
}

private void setupUI(View view) {
    rellay_timeline = view.findViewById(R.id.rellay_timeline);
    rellay_friends = view.findViewById(R.id.rellay_friends);
    rellay_chat = view.findViewById(R.id.rellay_chat);

    // The rest of the initialization code goes here...
}

您需要在super()的每个片段生命周期方法上调用@Override

我将UI初始化逻辑重构为一个单独的私有方法,以提高可读性,但没有必要这样做。我喜欢让片段生命周期方法尽可能保持细小和干净。