如何将值从工具栏微调器传递给ViewPager片段

时间:2017-01-23 23:07:52

标签: android android-fragments android-viewpager

我在ViewPager的工具栏onCreateOptionsMenu中有一个从DB填充的微调器,我想将它的值传递给fragment。

我想要实现的是根据微调器值更改片段内容。 我试图通过Bundle传递这个值,但它引发了我null object reference ...

我敢打赌,因为片段和它的东西加载速度比我的微调器更快地加载到Bundle。即便如此,我也不知道如何以正确的方式传递这个值......

提前感谢您的帮助!

编辑:

我找到了一种解决问题的方法,但我找到了另一种方法。我不能将valute发送给null以外的活动。

ChartsActivity.java

public class ChartsAcivity extends AppCompatActivity {

Context context = this;
int selected_car_id = 0;
DBHelper dbHelper;
String spinnerValue = null;

private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    Chart1Activity chart1 = (Chart1Activity) mSectionsPagerAdapter.getItem(0);
    if (spinnerValue != null) chart1.respond("test");
    else chart1.respond("OMG EMPTY AGAIN?!?!");

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_charts_acivity, menu);
    MenuItem carSpinner = menu.findItem(R.id.charts_activ_car_spinner);
    Spinner CarRefuelListSpinner = (Spinner) MenuItemCompat.getActionView(carSpinner);
    SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
    Cursor spinner_cursor = db.rawQuery("SELECT " + TableCar.NewCar.CAR_ID + " AS _id, " + TableCar.NewCar.CAR_NAME + " FROM " + TableCar.NewCar.TABLE_NAME, null);

    if(spinner_cursor.moveToFirst()) {

        String[] from = new String[]{TableCar.NewCar.CAR_NAME};
        int[] to = new int[]{android.R.id.text1};

        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, spinner_cursor, from, to);
        simpleCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        CarRefuelListSpinner.setAdapter(simpleCursorAdapter);

        CarRefuelListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);

                selected_car_id = Integer.valueOf(String.valueOf(id));

                String s = String.valueOf(selected_car_id);
                getSpinnerVal(s);
                //chart1.respond("test");


                //Chart1Activity chart1 = (Chart1Activity) mSectionsPagerAdapter.getItem(0);
                //chart1.respond(s);

            }

            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    else {
        ...
    }


    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    switch (item.getItemId()) {
        case android.R.id.home:

            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void getSpinnerVal (String value){

    spinnerValue = value;

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {


        switch (position){
            case 0:
                Chart1Activity chart1 = new Chart1Activity();
                return chart1;

            case 1:
                Chart2Activity chart2 = new Chart2Activity();
                return chart2;

            case 2:
                Chart3Activity chart3 = new Chart3Activity();
                return chart3;

            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "TEST 1";
            case 1:
                return "TEST 2";
            case 2:
                return "TEST 3";
        }
        return null;
    }
}
}

Chart1Activity.java

public class Chart1Activity extends Fragment implements FragmentCommunicator{

Context context;// = getActivity();
DBHelper dbHelper;
LineChart chart;
String car_id = null;
String test = null;

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

    if (car_id != null) {
        chart = (LineChart) getActivity().findViewById(R.id.chart1_line_fuel_usage);
        Toast.makeText(getActivity(), "ID = " + car_id, Toast.LENGTH_LONG).show();
        setData(car_id);
    }
    else Toast.makeText(getActivity(), "ID = null", Toast.LENGTH_LONG).show();

    return rootView;
}

@Override
public void respond(String data) {
    car_id = data;
}

public void setData(String car_id){

    dbHelper = new DBHelper(context);

    Cursor curChartFuelUsage = dbHelper.getChartFuelUsage(car_id);
    curChartFuelUsage.moveToFirst();

    int count = curChartFuelUsage.getCount();
    final String[] x_refuel_data = new String[count];
    final String[] x2_refuel_data = new String[count];
    Float[] y_fuel_usage = new Float[count];


    if (curChartFuelUsage.moveToFirst()){

        for (int i = 0 ; i < count ; i++){

            x_refuel_data[i] = curChartFuelUsage.getString(0);
            x2_refuel_data[i] = x_refuel_data[i].replace("-", "/");

            y_fuel_usage[i] = curChartFuelUsage.getFloat(1);
            curChartFuelUsage.moveToNext();
        }

        ArrayList<Entry> values = new ArrayList<Entry>();

        for (int i = 0 ; i < count ; i++){
            values.add(new Entry(i, y_fuel_usage[i]));
        }

        LineDataSet set1 = new LineDataSet(values,"test");
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setColors(new int[]{R.color.chartRed}, context);

        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(set1);

        LineData lineData = new LineData(dataSets);
        chart.setData(lineData);

        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return x2_refuel_data[(int)value];
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        };

        chart.getXAxis().setValueFormatter(formatter);
        chart.invalidate();


    }
    else Toast.makeText(context, "xxx.", Toast.LENGTH_LONG).show();

}
}

FragmentCommunicator.java

public interface FragmentCommunicator {

    public void respond (String data);
}

error

1 个答案:

答案 0 :(得分:0)

这与片段之间的通信相同...我建议您观看有关Fragment Communication的视频。我相信它会对你有所帮助并使你的代码更有条理