使用ViewPager从app中的Main Activity调用findViewById方法时出现NullPointerException

时间:2016-10-12 19:15:33

标签: java android android-fragments nullpointerexception android-viewpager

我尝试使用ViewPager编写应用程序,我想在我的应用程序中为TextView添加一个监听器。在Fragment代码中添加监听器很简单,但是如何在MainActivity中创建它而不会得到NullPointerException?

MainActivity:

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.TabHost;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener{
ViewPager viewPager;
TabHost tabHost;


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

    initTabHost();
    initViewPager();




    final TextView textView = (TextView) findViewById(R.id.txt_frag1);

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setText("Changed text");
        }
    });

}




private void initTabHost() {
    tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();

    String[] tabNames = {"FRAG1","FRAG2"};

    for(int i=0; i<tabNames.length;i++){
        TabHost.TabSpec tabSpec;
        tabSpec = tabHost.newTabSpec(tabNames[i]);
        tabSpec.setIndicator(tabNames[i]);
        tabSpec.setContent(new FakeContent(getApplicationContext()));
        tabHost.addTab(tabSpec);
    }
    tabHost.setOnTabChangedListener(this);
}

public class FakeContent implements TabHost.TabContentFactory{

    Context context;
    public FakeContent(Context mcontext){
        context=mcontext;
    }

    @Override
    public View createTabContent(String tag) {
        View fakeView = new View(context);
        fakeView.setMinimumHeight(0);
        fakeView.setMinimumWidth(0);
        return fakeView;
    }
}

private void initViewPager() {

    viewPager = (ViewPager) findViewById(R.id.view_pager);
    List<Fragment> listFragments = new ArrayList<Fragment>();
    listFragments.add(new BlankFragment());
    listFragments.add(new BlankFragment2());


    MyFragmentAdapter myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),listFragments);

    viewPager.setAdapter(myFragmentAdapter);
    viewPager.setOnPageChangeListener(this);
}


@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrollStateChanged(int selectedItem) {
    tabHost.setCurrentTab(selectedItem);
}

@Override
public void onTabChanged(String tabId) {
    int selectedItem = tabHost.getCurrentTab();
    viewPager.setCurrentItem(selectedItem);
    //TabHost ustawianie na środku
    HorizontalScrollView hScrollView = (HorizontalScrollView) findViewById(R.id.h_scroll_view);
    View tabView = tabHost.getCurrentTabView();
    int scrollPos = tabView.getLeft() -(hScrollView.getWidth() -tabView.getWidth())/2;
    hScrollView.smoothScrollTo(scrollPos,0);
}
}

MyFragmentAdapter:

public class MyFragmentAdapter extends FragmentPagerAdapter {

List<Fragment> listFragments;

public MyFragmentAdapter(FragmentManager fm, List<android.support.v4.app.Fragment> listFragments) {
    super(fm);
    this.listFragments = listFragments;
}

@Override
public android.support.v4.app.Fragment getItem(int position) {
    return listFragments.get(position);
}

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


}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_smart_led"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.pietr.viewpagerr.MainActivity">



<TabHost
    android:id="@+id/tabHost"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/h_scroll_view"
            android:fillViewport="true"
            android:scrollbars="none">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></TabWidget>
        </HorizontalScrollView>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v4.view.ViewPager
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/view_pager"
                ></android.support.v4.view.ViewPager>

        </FrameLayout>
    </LinearLayout>
</TabHost>

</LinearLayout>

片段是带有一个TextView的标准空白片段。

2 个答案:

答案 0 :(得分:0)

你的activity_main layout中没有id txt_frag1的视图。因此你得到一个NPE.First在activity_main xml中添加一个textview,然后在java中访问它。

答案 1 :(得分:0)

我有一个由fragment_blank.xml中定义的id txt_frag1创建的TextView。我想在Pager中显示这个片段,并从MainActivity访问它。