简体   繁体   中英

Android tabbed activity and java code?

I have 3 tabs in my tabbed activity. I created 3 classes that extend Fragment and added my layouts. When I run it, it works fine. So I added some EditText widgets and a Button to my second tab. My question is : where do I put java code, for example, to handle onClickListener for that button. I tried to do it in that main tabbed activity class but then the app crashed.

You must add button click code to respective Fragment ie second tab in your case. Don't write code on activity which host that fragment.

You can put that code in the relevant fragment of tabbed activity. Application will crash because activity can not access the views which are inflated in fragment. You can do like this :

public class PageFragment extends Fragment {
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        PageFragment fragment = new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        TextView textView = (TextView) view;
        textView.setText("Fragment #" + mPage);
        return view;
    }
}

For more check this tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM