如何从另一个类中设置文本或查找ViewById?

时间:2015-10-24 10:17:30

标签: android android-fragments android-activity

我对编码完全陌生 并一直在尝试制作药物剂量计算器 该应用程序的想法是在顶部有一个Seekbar供用户调整体重 这样所有的药物都会自发地显示计算的剂量。

使用一个MainActivity和一个XML文件进行第一次试用时,我成功尝试了 (参考图片http://i.stack.imgur.com/KhbN4.jpg

然而,当我第二次尝试使用可滑动视图制作标签布局时,应用程序在触摸Seekbar时关闭。 (参考图片http://i.stack.imgur.com/72SYw.png

我一直在关注androidhive的这个教程。

那些用于计算和显示的代码应该在MainActivity类还是片段类中完成? 我想我的主要问题是我不知道如何从另一个类中设置文本或查找ViewById。任何帮助表示赞赏。

使用新信息进行修改: 从我第二次尝试的onProgressChanged方法删除这三行后,Seekbar再次工作以显示滑块的当前值。但是,一旦我放回这三行来更新textView,一旦我触摸Seekbar,它就会强制关闭                 mincefaclordose.setText(String.valueOf(minCefaclorDose)+" mg Q8H");                 maxcefaclordose.setText(String.valueOf(maxCefaclorDose)+" mg Q8H");                 zithromaxdose.setText(String.valueOf(zithromaxDose)+" mg Q24H");

我可以根据要求提供更多信息。

  

修复textView ID后的新Logcat

     

10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:FATAL EXCEPTION:main   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:进程:com.example.android.b,PID:9910   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:java.lang.NullPointerException:尝试调用虚方法' void android.widget.TextView.setText(java.lang .CharSequence)'在null对象引用上   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at com.example.android.b.MainActivity $ 1.onProgressChanged(MainActivity.java:58)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.SeekBar.onProgressRefresh(SeekBar.java:93)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.ProgressBar.doRefreshProgress(ProgressBar.java:1303)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.ProgressBar.refreshProgress(ProgressBar.java:1315)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.ProgressBar.setProgress(ProgressBar.java:1361)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.AbsSeekBar.trackTouchEvent(AbsSeekBar.java:666)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.widget.AbsSeekBar.onTouchEvent(AbsSeekBar.java:595)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.View.dispatchTouchEvent(View.java:9294)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at com.android.internal.policy.PhoneWindow $ DecorView.superDispatchTouchEvent(PhoneWindow.java:2403)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.app.Activity.dispatchTouchEvent(Activity.java:2765)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at com.android.internal.policy.PhoneWindow $ DecorView.dispatchTouchEvent(PhoneWindow.java:2364)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.View.dispatchPointerEvent(View.java:9514)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4230)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ ViewPostImeInputStage.onProcess(ViewRootImpl.java:4096)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.deliver(ViewRootImpl.java:3642)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.onDeliverToNext(ViewRootImpl.java:3695)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.forward(ViewRootImpl.java:3661)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ AsyncInputStage.forward(ViewRootImpl.java:3787)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.apply(ViewRootImpl.java:3669)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ AsyncInputStage.apply(ViewRootImpl.java:3844)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.deliver(ViewRootImpl.java:3642)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.onDeliverToNext(ViewRootImpl.java:3695)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.forward(ViewRootImpl.java:3661)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.apply(ViewRootImpl.java:3669)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ InputStage.deliver(ViewRootImpl.java:3642)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5922)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5896)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5857)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.ViewRootImpl $ WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6025)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)   10-24 19:07:31.865 9910-9910 / com.example.android.b E / AndroidRuntime:在android.view.InputEventRe

//my success code
public class MainActivity extends AppCompatActivity {
SeekBar seekBar;
TextView BW;
TextView maxcefaclordose;
TextView mincefaclordose;
TextView zithromaxdose;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    seekBar = (SeekBar) findViewById(R.id.seekbar);
    BW = (TextView) findViewById(R.id.textView);
    mincefaclordose = (TextView) findViewById(R.id.cefaclormin);
    maxcefaclordose = (TextView) findViewById(R.id.cefaclormax);
    zithromaxdose = (TextView) findViewById(R.id.zithromaxdose);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            double trueBW = (double)(progress)/10;
            long maxCefaclorDose = Math.round(trueBW*40/3);
            long minCefaclorDose = Math.round(trueBW*20/3);
            long zithromaxDose =  Math.round(trueBW*10);

            BW.setText(String.valueOf(trueBW));
            mincefaclordose.setText(String.valueOf(minCefaclorDose)+"mg  Q8H");
            maxcefaclordose.setText(String.valueOf(maxCefaclorDose)+"mg  Q8H");
            zithromaxdose.setText(String.valueOf(zithromaxDose)+"mg  Q24H");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }

    });
};

}

//here start the code I fail on second trial

public class MainActivity extends AppCompatActivity {
SeekBar seekBar;
TextView BW;
TextView maxcefaclordose;
TextView mincefaclordose;
TextView zithromaxdose;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    seekBar = (SeekBar) findViewById(R.id.seekbar);
    BW = (TextView) findViewById(R.id.textView);
    mincefaclordose = (TextView) findViewById(R.id.cefaclormin);
    maxcefaclordose = (TextView) findViewById(R.id.cefaclormax);
    zithromaxdose = (TextView) findViewById(R.id.zithromaxdose);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);


    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            double trueBW = (double)(progress)/10;
            long maxCefaclorDose = Math.round(trueBW*40/3);
            long minCefaclorDose = Math.round(trueBW*20/3);
            long zithromaxDose =  Math.round(trueBW*10);

            BW.setText(String.valueOf(trueBW));
            mincefaclordose.setText(String.valueOf(minCefaclorDose)+"mg  Q8H");
            maxcefaclordose.setText(String.valueOf(maxCefaclorDose)+"mg  Q8H");
            zithromaxdose.setText(String.valueOf(zithromaxDose)+"mg  Q24H");

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new URTI(), "URTI");
    adapter.addFragment(new AntimicrobialFragment(), "Anti-\nmicrobials");
    adapter.addFragment(new Others(), "Others");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

//我的activity_main.xml     

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    <LinearLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10sp"
        android:layout_marginBottom="10sp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:paddingLeft="8sp"
            android:layout_width="40sp"
            android:layout_height="wrap_content"
            android:text="6.0" />

        <TextView
            android:id="@+id/kg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/textView"
            android:text="kg" />

        <SeekBar
            android:id="@+id/seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/kg"
            android:max="500"
            android:progress="60" />
    </LinearLayout>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

1 个答案:

答案 0 :(得分:1)

您收到的TextView 错误ID的NPE(NullPointerException)bcoz

获取成功代码的部分

setContentView(R.layout.activity_main);

seekBar = (SeekBar) findViewById(R.id.seekbar);
BW = (TextView) findViewById(R.id.textView);

获取失败代码的部分

setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekbar);
BW = (TextView) findViewById(R.id.BWtextView);

正如您在上面两种情况中所见,您使用activiy_main作为布局,但BW TextView的ID不同,因此使用R.id.textView代替R.id.BWtextView。但是如果你想要R.id.BWtextView,那么请确保在activity_main布局中将id保持为相同

  

建议:请准确理解来自here的NPE是什么。和   你可以轻松修复它,因为在logcat报告中你可以   显然是给予这个NPE并导致崩溃的线   申请。

更新根据以下评论
我不知道你已经解决了传递价值的问题......不管怎样 解决方案1 ​​:在片段中创建所需TextView的全局变量并编写方法,例如......

public class MainActivityFragment extends Fragment {
  //your code
  TextView textView;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  //your code
  textView = .....findViewById(R.id.texViewId)
  }

  //your code

  void setTextView(String text){
      textView.setText(text);
  }

然后在您的Activity中而不是直接执行adapter.addFragment(new AntimicrobialFragment(), "Anti-\nmicrobials");为片段创建全局变量,在Listener中您可以执行以下操作。

Fragment antimicrobialFragment;  
//your code 

antimicrobialFragment = new AntimicrobialFragment(); 
//your code 

//Inside setupViewPagerAdapter
adapter.addFragment(antimicrobialFragment, "Anti-\nmicrobials");

//Inside onProgressChanged in onSeekBarChangeListener
if(null != antimicrobialFragment && antimicrobialFragment .isVisible()){
   ((AntimicrobialFragment)antimicrobialFragment ).setTextView("Sample Text");
} else {
   //just to verify 
   Toast.makeText(getBaseContext(),"Fragment is notVisible",Toast.LENGTH_LONG).show();
}

解决方案2 使用带片段的自定义侦听器。