在SlidingTabslayout中的两个选项卡片段之间传递数据

时间:2015-07-19 15:37:35

标签: java android android-fragments tabs

我有一个应用程序,它有一个主要活动,而这个活动又有两个标签。每个标签都是一个片段。第一个选项卡有一个editText和一个按钮,按下按钮,用户输入的文本必须显示在仅包含一个textView的第二个选项卡片段上。我正在使用监听器传递数据但由于某种原因,当我按下提交按钮时应用程序崩溃。任何帮助,将不胜感激。这是我的代码:

MainActivity.java

    public class MainActivity extends AppCompatActivity implements OnEditTextListener {

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[] = {"Home", "Events"};
    int Numboftabs = 2;

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

        // Creating The Toolbar and setting it as the Toolbar for the activity

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


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.ColorPrimary);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void OnEditText(String data) {
        Tab2 newFragment = (Tab2)adapter.getItem(1);
        newFragment.updateDisplay(data);
    }
}

Tab1.java

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class Tab1 extends Fragment
{
    public interface OnEditTextListener {
        public void OnEditText(String data);
    }

    OnEditTextListener editTextListener = null;
    EditText edtText;
    Button btnSubmit;

    String val;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            editTextListener = (OnEditTextListener) activity;
        } catch (ClassCastException ex) {
            ex.printStackTrace();
        }
    }

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        edtText = (EditText)getActivity().findViewById(R.id.edtText);
        btnSubmit = (Button)getActivity().findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                val = edtText.getText().toString();
                editTextListener.OnEditText(val);
            }
        });
    }
}

Tab2.java

public class Tab2 extends Fragment {

    public static final String TAG = "DATA";
    public static final String SAVE = "NBHJB";
    String newdata = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (savedInstanceState != null)
            savedInstanceState.getInt(SAVE);

        return inflater.inflate(R.layout.second_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState != null) {
            savedInstanceState.getString(SAVE);
        }
    }

    public void updateDisplay(String data) {
        newdata = data;
        TextView randomData = (TextView) getActivity().findViewById(R.id.txtView1);
        randomData.setText(newdata);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString(SAVE, newdata);
    }

MainActivity.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <View
        android:layout_height="2dip"
        android:background="@color/tabsScrollColor"
        android:layout_width="wrap_content" />

    <com.example.regi.tabsprove.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/prove"
        android:elevation="2dp" />



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


</LinearLayout>

second_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="10dp"
        android:text="Default Text"
        android:textSize="20dp" />

</LinearLayout>

这是我得到的错误

java.lang.NullPointerException
            at com.example.regi.tabsprove.Tab2.updateDisplay(Tab2.java:36)
            at com.example.regi.tabsprove.MainActivity.OnEditText(MainActivity.java:79)
            at com.example.regi.tabsprove.Tab1$1.onClick(Tab1.java:51)
            at android.view.View.performClick(View.java:4198)
            at android.view.View$PerformClick.run(View.java:17158)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4918)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
            at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

我非常确定第Tab2 newFragment = (Tab2)adapter.getItem(1);行正在创建一个新的Tab2实例,而不是为您提供所需的片段。您应该找到一种更好的方法来获取ViewPager为您构建的Fragment实例;我确定这post可以帮到你。

答案 1 :(得分:0)

我发现你的设计比常规数据传递复杂一点。从日志中,问题是程序无法在第二个片段中找到txtView1。使用bundle传递数据总是一个好习惯。

我希望以下更改可以解决您的问题,但这不是最好的方法。

在newData旁边声明TextView

Call to a member function fetch_assoc() on a non-object...

在onCreateView()

中初始化它
public static final String TAG = "DATA";
public static final String SAVE = "NBHJB";
String newdata = "";
TextView randomData;

更改updateDisplay功能

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (savedInstanceState != null)
        savedInstanceState.getInt(SAVE);

    View rootView = inflater.inflate(R.layout.second_fragment, container, false);

    randomData = (TextView) rootView.findViewById(R.id.txtView1);

    return rootView;
}

确保您没有任何其他与txtView1具有相同ID的项目。

答案 2 :(得分:0)

以下是可能遇到同一问题的每个人的解决方案:

public static String makeFragmentName(int containerViewId, long id) {
        return "android:switcher:" + containerViewId + ":" + id;
    }

    public @Nullable
    Fragment getFragmentForPosition(int position)
    {
        String tag = makeFragmentName(pager.getId(), position);
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
        return fragment;
    }

    @Override
    public void OnEditText(String data) {
        Tab2 tab2 = (Tab2)getFragmentForPosition(1);
        tab2.updateDisplay(data);
    }

此代码转到MainActivity.java