1

我使用片段在三个选项卡中更改了我的 activity_main.xml 布局。我想像以前一样访问 MainActivity 中的所有选项卡组件,但我得到了 NullPointersException。我在这里做错了什么。谢谢!

我的片段代码:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class FragMent3 extends Fragment {

    EditText textBox;

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

        View view = inflater.inflate(R.layout.logbook_view, null);

        return view;
    }   
}

第三个布局选项卡的代码:

<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" >

   <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="Send request"
        android:onClick="onSendButtonClicked" />

   <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Write request.."
        android:ems="10" />

</LinearLayout>

MainActivity 部分代码:

@SuppressLint("NewApi")
public class MainActivity extends Activity implements TabListener {
    RelativeLayout rl;


    EditText textBox;
    static int x;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textBox = (EditText)findViewById(R.id.editText1);

        try {
            rl = (RelativeLayout) findViewById(R.id.mainLayout);

            fragMentTra = getFragmentManager().beginTransaction();
            ActionBar bar = getActionBar();
            bar.addTab(bar.newTab().setText("Info").setTabListener(this));
            bar.addTab(bar.newTab().setText("Pilot").setTabListener(this));
            bar.addTab(bar.newTab().setText("Logbook").setTabListener(this));

            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
                    | ActionBar.DISPLAY_USE_LOGO);
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayShowHomeEnabled(true);
            bar.setDisplayShowTitleEnabled(false);
            bar.show();

        } catch (Exception e) {
            e.getMessage();
        }
        /**
         * Hiding Action Bar
         */
    }

    FragMent1 fram1;
    FragmentTransaction fragMentTra = null;
    FragMent2 fram2;
    FragMent3 fram3;


    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }*/

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {

        if (tab.getText().equals("Info")) {
            try {
                rl.removeAllViews();
            } catch (Exception e) {
            }
            fram1 = new FragMent1();
            fragMentTra.addToBackStack(null);
            fragMentTra = getFragmentManager().beginTransaction();
            fragMentTra.add(rl.getId(), fram1);
            fragMentTra.commit();
        } else if (tab.getText().equals("Pilot")) {
            try {
                rl.removeAllViews();
            } catch (Exception e) {
            }
            fram2 = new FragMent2();
            fragMentTra.addToBackStack(null);
            fragMentTra = getFragmentManager().beginTransaction();
            fragMentTra.add(rl.getId(), fram2);
            fragMentTra.commit();
        } else if (tab.getText().equals("Logbook")) {
            try {
                rl.removeAllViews();
            } catch (Exception e) {
            }
            fram3 = new FragMent3();
            fragMentTra.addToBackStack(null);
            fragMentTra = getFragmentManager().beginTransaction();
            fragMentTra.add(rl.getId(), fram3);
            fragMentTra.commit();
        }

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }

    public void onSendButtonClicked(View view) {

        textBox.setText("some text on third tab EditText");
    }

日志猫:

05-06 12:42:19.993: E/AndroidRuntime(29991): FATAL EXCEPTION: main
05-06 12:42:19.993: E/AndroidRuntime(29991): java.lang.IllegalStateException: Could not execute method of the activity
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.view.View$1.onClick(View.java:3103)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.view.View.performClick(View.java:3574)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.view.View$PerformClick.run(View.java:14293)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.os.Handler.handleCallback(Handler.java:605)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.os.Looper.loop(Looper.java:137)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.app.ActivityThread.main(ActivityThread.java:4441)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at java.lang.reflect.Method.invokeNative(Native Method)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at java.lang.reflect.Method.invoke(Method.java:511)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at dalvik.system.NativeStart.main(Native Method)
05-06 12:42:19.993: E/AndroidRuntime(29991): Caused by: java.lang.reflect.InvocationTargetException
05-06 12:42:19.993: E/AndroidRuntime(29991):    at java.lang.reflect.Method.invokeNative(Native Method)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at java.lang.reflect.Method.invoke(Method.java:511)
05-06 12:42:19.993: E/AndroidRuntime(29991):    at android.view.View$1.onClick(View.java:3098)
05-06 12:42:19.993: E/AndroidRuntime(29991):    ... 11 more
05-06 12:42:19.993: E/AndroidRuntime(29991): Caused by: java.lang.NullPointerException
05-06 12:42:19.993: E/AndroidRuntime(29991):    at com.example.colibri2bbui.MainActivity.onSendButtonClicked(MainActivity.java:201)
05-06 12:42:19.993: E/AndroidRuntime(29991):    ... 14 more
4

3 回答 3

2

The way you are doing your 'TAB' implementation is totally wrong. First of all, you should use FrameLayout as parent view to add/replace your Fragments. Second thing is that the logic in onTabSelected should be changed. Here is an example which is the proper way to use Tab Navigation in ActionBar.

First create your main.xml, where your Fragments will be added/attached :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Second you can create your tabs and add TabListener to them :

mMyActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

ActionBar.Tab mFirstTab = mMyActionBar.newTab();
mFirstTab.setText("First Tab");
mFirstTab.setTabListener(this);
mMyActionBar.addTab(mFirstTab);

ActionBar.Tab mSecondTab = mMyActionBar.newTab();
mSecondTab.setText("Second Tab");
mSecondTab.setTabListener(this);
mMyActionBar.addTab(mSecondTab);

ActionBar.Tab mThirdTab = mMyActionBar.newTab();
mThirdTab.setText("Third Tab");
mThirdTab.setTabListener(this);
mMyActionBar.addTab(mThirdTab);

and create your TabListener like this :

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // Check if the fragment is already initialized
    if (mFirstTab == null) {
        // If not, instantiate and add it to the activity
        mFirstTab = Fragment.instantiate(mActivity, mClass.getName());
        ft.add(android.R.id.content, mFirstTab, mTag);
    } else {
        // If it exists, simply attach it in order to show it
        ft.attach(mFirstTab);
    }
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    if (mFirstTab != null) {
        // Detach the fragment, because another one is being attached
        ft.detach(mFirstTab);
    }
}

public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // User selected the already selected tab. Usually do nothing.
}

And about NullPointerException in your code, as I can see your EditText : textBox = (EditText)findViewById(R.id.editText1); which you are trying to use in your MainActivity is declared in your third's tab layout. This EditText should be declared and used in your FragMent3, not in MainActivity .

Hope this answer help you!

于 2013-05-06T15:37:54.857 回答
0

已编辑:您可以删除此行

textBox = (EditText)findViewById(R.id.editText1);

onSendButtonClicke只需在您的方法中使用作为参数传递的视图:

public void onSendButtonClicked(View view) {

    ((EditText)view).setText("some text on third tab EditText");
}
于 2013-05-06T10:32:09.823 回答
0

我猜 EditText 是在片段的布局文件中定义的。在这种情况下,您无法直接访问它,findViewById但您需要获取片段的视图,然后调用view.findViewById

于 2013-05-06T11:06:39.740 回答