【问题标题】:Android add TextViews into fragmentAndroid在片段中添加TextView
【发布时间】:2014-03-17 16:41:51
【问题描述】:

我有 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 的方法,一切都很好。问题出在片段中。*

【问题讨论】:

  • 发布崩溃的完整堆栈跟踪
  • 我添加了我的日志,但我认为它没有用。
  • 你不是一遍又一遍地将文本添加到同一个视图中吗?
  • 你在哪里设置这个片段?您能否展示设置此片段的活动?
  • 请粘贴您的 MainActivity 并突出显示第 244 行

标签: java android loops crash textview


【解决方案1】:

问题出在 onCreateView 方法中,您在片段父亲 (MainActivity) 中找到了 LinearLayout,但您必须在刚刚膨胀的视图中找到。

替换这一行:

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

通过

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

一切都会好起来的!

【讨论】:

    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多