我如何在Android中使用findViewById()?

时间:2018-10-03 18:49:39

标签: java android

基本上,问题在于,当您想使用方法“ FindViewById”或“ GetSystemService”或其他方法不允许我使用时。

他只允许我在MainActivity中使用它们,我想知道如何解决这个问题。

我是android Studio的新手,我基本上是在学习

MainAtivity

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                tap1alarmas tap1 = new tap1alarmas();
                return tap1;
            case 1:
                tap2tips tap2 = new tap2tips();
                return tap2;
            case 2:
                tap3estadisticas tap3 = new tap3estadisticas();
                return tap3;
            default:
                return null;

        }
    }

“ Tap1alarmas”片段

import android.app.AlarmManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;


public class tap1alarmas extends Fragment {


AlarmManager alarm_manager;
TimePicker alarm_timepicker;
TextView update_text;
tap1alarmas context;


private MainActivity.SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

this.context = this;

//Inicizaliar alarmmanager
alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);

//Inicializar timepicker

alarm_timepicker = (TimePicker) findViewById(R.id.TimePicker);

//Text uptate`enter code here`

update_text = (TextView) findViewById(R.id.update_text);

1 个答案:

答案 0 :(得分:0)

如果您尝试在EOF中使用findViewById,请首先确保使用Fragment,并在最后返回视图。

在此处查看差异:Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

这是一个例子:

onCreateView()

@Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_single_image, parent, false); alarm_timepicker = (TimePicker) rootView.findViewById(R.id.TimePicker); // your widgets with rootView prefix return rootView; } 是这里的重点。因此,如果您要声明任何小部件(或其他),请在这种情况下使用rootView作为前缀,然后再使用rootView引用id。