Android将TextViews添加到片段中

时间:2014-03-17 16:41:52

标签: java android loops crash textview

我有Android应用程序。我想在Fragment中添加一些TextView。但它一开始就崩溃了。 THX寻求帮助。

这是我的Java代码:

public class MyClass extends Fragment implements LocationListener {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public MyClass() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                container, false);
        LinearLayout myLayout = (LinearLayout) findViewById(R.id.hl);

        LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        for(int l=0; l<4; l++)
        {
            TextView a = new TextView(MainActivity.this);
            a.setTextSize(15);
            a.setLayoutParams(lp);
            a.setId(l);
            a.setText((l + 1) + ": something");
            myLayout.addView(a);
        }

        return rootView;
    }

这是我的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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<LinearLayout
    android:id="@+id/hl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffdf33"
    android:orientation="vertical" >
</LinearLayout>

从adb -d logcat |输出grep najdibar(我的应用名称)

    W/ADB_SERVICES(  122): create_local_service_socket() name=shell:pm path com.example.najdibar
W/ADB_SERVICES(  122): create_local_service_socket() name=shell:am start -n com.example.najdibar/com.example.najdibar.MainActivity -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
I/ActivityManager(  337): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.najdibar/.MainActivity u=0} from pid 839
I/ActivityManager(  337): Start proc com.example.najdibar for activity com.example.najdibar/.MainActivity: pid=850 uid=10086 gids={3003, 1015, 1028}
V/ActivityManager(  337): Binding process pid 850 to record ProcessRecord{42db8a10 850:com.example.najdibar/u0a86}
V/ActivityManager(  337): New app record ProcessRecord{42db8a10 850:com.example.najdibar/u0a86} thread=android.os.BinderProxy@42f39f98 pid=850
I/BufferQueue(   99): [Starting com.example.najdibar] setDefaultBufferSize: w=600, h=976
V/ActivityManager(  337): ACT-Launching: ActivityRecord{42730430 com.example.najdibar/.MainActivity}
I/BufferQueue(   99): [Starting com.example.najdibar] connect: api=2
I/BufferQueue(   99): [Starting com.example.najdibar] setSynchronousMode: enabled=1
I/BufferQueue(   99): [Starting com.example.najdibar] createGraphicBuffer before(NULL) after(0x42bfd160, handle=0x42c324b8, w=600, h=976, f=1)
D/dalvikvm(  850): open_cached_dex_file : /data/app/com.example.najdibar-1.apk /data/dalvik-cache/data@app@com.example.najdibar-1.apk@classes.dex
D/ActivityThread(  850): BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{422828b8 com.example.najdibar}}
V/ActivityManager(  337): com.example.najdibar/.MainActivity: task=TaskRecord{42e8e168 #142 A com.example.najdibar U 0}
D/ActivityThread(  850): ACT-AM_ON_RESUME_CALLED ActivityRecord{42283d80 token=android.os.BinderProxy@422835a8 {com.example.najdibar/com.example.najdibar.MainActivity}}
D/ActivityThread(  850): ACT-LAUNCH_ACTIVITY handled : 0 / ActivityRecord{42283d80 token=android.os.BinderProxy@422835a8 {com.example.najdibar/com.example.najdibar.MainActivity}}
E/AndroidRuntime(  850):    at com.example.najdibar.MainActivity$NejblizsiBary.onCreateView(MainActivity.java:241)
W/ActivityManager(  337):   Force finishing activity com.example.najdibar/.MainActivity
D/AES     (  337):     process : com.example.najdibar
D/AES     (  337):      module : com.example.najdibar v1 (1.0)
D/AEE/LIBAEE(  337): shell: raise_exp(2, 850, -1361051648, com.example.najdibar, 0x0x594c3640, 0x0x0)
W/ActivityManager(  337): Activity pause timeout for ActivityRecord{42730430 com.example.najdibar/.MainActivity}
V/ActivityManager(  337): Enqueueing pending finish: ActivityRecord{42730430 com.example.najdibar/.MainActivity}
V/ActivityManager(  337): com.example.najdibar/.MainActivity: task=TaskRecord{42e8e168 #142 A com.example.najdibar U 0}
V/ActivityManager(  337): com.example.najdibar/.MainActivity: task=TaskRecord{42e8e168 #142 A com.example.najdibar U 0}
V/ActivityManager(  337): com.example.najdibar/.MainActivity: task=TaskRecord{42e8e168 #142 A com.example.najdibar U 0}
I/WindowState(  337): WIN DEATH: Window{434f3880 com.example.najdibar/com.example.najdibar.MainActivity paused=false}
I/ActivityManager(  337): Process com.example.najdibar (pid 850) has died.
V/ActivityManager(  337): Dying app: ProcessRecord{42db8a10 850:com.example.najdibar/u0a86}, pid: 850, thread: android.os.BinderProxy@42f39f98
V/ActivityManager(  337): Removing app ProcessRecord{42db8a10 0:com.example.najdibar/u0a86} from list [ActivityRecord{42328ff8 org.jtb.alogcat/.LogActivity}, ActivityRecord{42274ac0 com.android.launcher/com.android.launcher2.Launcher}] with 2 entries
V/ActivityManager(  337): Removing app ProcessRecord{42db8a10 0:com.example.najdibar/u0a86} from list [] with 0 entries
V/ActivityManager(  337): Removing app ProcessRecord{42db8a10 0:com.example.najdibar/u0a86} from list [] with 0 entries
V/ActivityManager(  337): Removing app ProcessRecord{42db8a10 0:com.example.najdibar/u0a86} from list [] with 0 entries
V/ActivityManager(  337): Removing app ProcessRecord{42db8a10 0:com.example.najdibar/u0a86} from list [] with 0 entries
I/BufferQueue(   99): [Starting com.example.najdibar] disconnect: api=2
I/SurfaceTexture(   99): [Starting com.example.najdibar] [virtual void android::SurfaceTexture::onBuffersReleased()] mCurrentTexture:0, mCurrentBuf:0x42bfd160
I/BufferQueue(   99): [Starting com.example.najdibar] getReleasedBuffers: returning mask 0xffffffff
I/BufferQueue(   99): [Starting com.example.najdibar] consumerDisconnect
I/BufferQueue(   99): [Starting com.example.najdibar] ~BufferQueue
W/ActivityManager(  337): Activity destroy timeout for ActivityRecord{42730430 com.example.najdibar/.MainActivity}

设置片段:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        switch (position) {
        case 0: {
            Fragment fragment = new MyClass();
            Bundle args = new Bundle();
            args.putInt(MyClass.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        case 1: {
            Fragment fragment3 = new Mapa();
            Bundle args = new Bundle();
            args.putInt(Mapa.ARG_SECTION_NUMBER, position + 2);
            fragment3.setArguments(args);
            return fragment3;
        }

        case 2: {
            Fragment fragment2 = new OblibeneBary();
            Bundle args = new Bundle();
            args.putInt(OblibeneBary.ARG_SECTION_NUMBER, position + 3);
            fragment2.setArguments(args);
            return fragment2;
        }

        default:
            return null;
        }
    }

我有这个例外:

    03-18 10:42:58.660: E/AndroidRuntime(17598): FATAL EXCEPTION: main
03-18 10:42:58.660: E/AndroidRuntime(17598): java.lang.NullPointerException
03-18 10:42:58.660: E/AndroidRuntime(17598):    at com.example.najdibar.MainActivity$NejblizsiBary.onCreateView(MainActivity.java:244)

第244行是将TextView添加到LinearLayout myLayout.addView(a);

的行

修改 * 如果我创建了从ActionBar单击按钮后添加TextView的方法,一切都很好。问题出现在片段中。 *

2 个答案:

答案 0 :(得分:2)

变化:

 View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                container, false);
        LinearLayout myLayout = (LinearLayout) findViewById(R.id.hl);

 View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                container, false);
        LinearLayout myLayout = (LinearLayout) rootView.findViewById(R.id.hl);

答案 1 :(得分:2)

问题出在onCreateView上的方法中,你发现LinearLayout进入了片段父(MainActivity),但你必须在刚刚膨胀的视图中找到它。

替换此行:

LinearLayout myLayout = (LinearLayout) findViewById(R.id.hl);

通过

LinearLayout myLayout = (LinearLayout) rootView.findViewById(R.id.hl);

一切都会奏效!