-1

Tabs機器人:從活動

更新選項卡布局(片段)textviews我創建使用tablayout和viewpager標籤視圖。我爲每個選項卡使用一個片段。在我的MainActivity中,我通過藍牙從設備獲取一些值。這些值是作爲單個字符串接收的,我將其拆分並將其設置爲相應的選項卡。但是當我嘗試從我的活動中爲片段中的textview調用setText方法時,我得到一個NullPointerException。 任何人都可以告訴我如何更新從我的MainActivity每個片段的文字瀏覽?就像,如果我選擇溫度選項卡,應使用MainActivity中的值更新溫度片段中的textview。請幫助

活動

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { 

    Handler bluetoothIn; 
    private static TextView tmpF, humF, CoF; 
    String tempGL, HumGL, coGL, devname; 
    double dblTemp, dblCo; 
    final int handlerState = 0; // used to identify handler message 
    private BluetoothAdapter btAdapter = null; 
    private TabLayout tabLayout; 
    private ViewPager viewPager; 

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

tmpF = (TextView)findViewById(R.id.txt_temp_val); 
humF = (TextView)findViewById(R.id.txt_hum_val); 
co = (TextView)findViewById(R.id.txt_co_val); 

//Adding toolbar to the activity 
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
setSupportActionBar(toolbar); 
//Initializing the tablayout 
tabLayout = (TabLayout) findViewById(R.id.tabLayout); 
//Initializing viewPager 
viewPager = (ViewPager) findViewById(R.id.pager); 
//Adding the tabs using addTab() method 
tabLayout.addTab(tabLayout.newTab().setText("Temperature")); 
tabLayout.addTab(tabLayout.newTab().setText("Humidity")); 
tabLayout.addTab(tabLayout.newTab().setText("CO")); 
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); 

//Creating our pager adapter 
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount()); 

//Adding adapter to pager 
viewPager.setAdapter(adapter); 
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); 
//Adding onTabSelectedListener to swipe views 
tabLayout.setOnTabSelectedListener(this); 

bluetoothIn=new Handler() { 

    String readMessage; 
    String[] values = new String[]{""}; 

    public void handleMessage(android.os.Message msg) { 

     if (msg.what == handlerState) { 

      readMessage = (String) msg.obj; 
      values = readMessage.split("#"); 
      for (int j = 0; j < values.length; j++) { 

       int rem = j % 3; 

       if (rem == 0) { 

        tmpF.setText(values[j] + " C"); 
        tempGL = String.valueOf(values[j]); 

        try { 
         dblTemp = Double.parseDouble(tempGL); 
        } catch (NumberFormatException e) { 
         e.printStackTrace(); 
        } 

       } else if (rem == 1) { 

        CoF.setText(values[j] + " ppm"); 
        coGL = values[j]; 
        try { 
         dblCo = Double.parseDouble(coGL); 
        } catch (NumberFormatException e) { 
         e.printStackTrace(); 
        } 

       } else if (rem == 2) { 
        humF.setText(values[j] + " %"); 
        HumGL = values[j]; 
       } 
      } 
     } 
    } 
}; 

btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth 
} 

@Override 
public void onTabSelected(TabLayout.Tab tab) { 
// mViewPager.setCurrentItem(tab.getPosition()); 

} 

@Override 
public void onTabUnselected(TabLayout.Tab tab) { 

} 

@Override 
public void onTabReselected(TabLayout.Tab tab) { 

} 
} 

TAB1

public class OneFragment extends Fragment { 

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

} 
} 

fragment_one.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="shinil.tablayout.OneFragment" 
android:id="@+id/rltnvnv"> 

<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="Temperature" 
android:textSize="40dp" 
android:textStyle="bold" 
android:id="@+id/txt_temp_val" 
android:layout_centerInParent="true"/> 

</RelativeLayout> 

logcat的

Caused by: java.lang.NullPointerException: Attempt to invoke virtual  method 'void  android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference at shinil.airopure.MainActivity.onCreate(MainActivity.java:194) 

frag_home.xml

<LinearLayout 
    android:id="@+id/main_layout" 
    android:orientation="vertical" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity"> 


    <android.support.v7.widget.Toolbar 
android:id="@+id/toolbar" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:background="?attr/colorPrimary" 
android:minHeight="?attr/actionBarSize" 
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> 


    <android.support.design.widget.TabLayout 
    android:id="@+id/tabLayout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="?attr/colorPrimary" 

    android:minHeight="?attr/actionBarSize" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> 


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

</LinearLayout> 
+0

請問您可以發佈您的代碼嗎? –

+0

請顯示activity_frag_home.xml – Pooya

+0

@Pooya更新! –

回答

1

嗨,我不知道如果我正確理解你的問題,但讓我嘗試幫助。

我假設你ViewPager適配器從FragmentStatePagerAdapter

首先在你的尋呼機適配器擴展定義您的片段一SparseArray象下面這樣:

SparseArray<Fragment> myPagerFragments= new SparseArray<>(); 

在您的適配器instantiateItem方法的片段添加到您的sparsearray。

@Override 
public Object instantiateItem(ViewGroup container, int position) { 
     Fragment fragment = (Fragment) super.instantiateItem(container, position); 
     myPagerFragments.put(position, fragment); 
     return fragment; 
    } 

並在您的destroyItem方法中從您的sparsearray中刪除您的片段。

@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
     myPagerFragments.remove(position); 
     super.destroyItem(container, position, object); 
    } 

添加到您的adpater一個方法,它返回您的尋呼機片段likew如下:

public Fragment getRegisteredFragment(int position) { 
     return myPagerFragments.get(position); 
    } 

在您的片段定義哪些改變你的TextView文本likew下面的公共方法:

public void setText(String text){ 
    myTextView.setText(text); 
} 

在您的活動中定義您的適配器,並向您的ViewPager添加onPageChangeListener,如下所示:

MyPagerAdapter mAdapter = new MyPagerAdapter(context,items); 
myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
    @Override 
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

    } 

    @Override 
    public void onPageSelected(int position) { 
     Fragment myPagerFragment = mAdapter.getRegisteredFragment(position); 
     if(fragment != null){ 
      ((YourFragment)fragment).setText("Hello World!"); 
     } 
    } 

    @Override 
    public void onPageScrollStateChanged(int state) { 

    } 
}); 

我希望這會幫助你。祝你好運。

+0

我試過了你的代碼,但仍然得到了NPE。無論如何感謝您的回答 –

+0

這是一個有效的解決方案,關於如何更改附加到viewpager的片段中的數據。正如我們在logcat中看到的,viewpager爲null。所以你不能設置適配器。 – savepopulation