java - Android 将 TextViews 添加到 fragment 中

标签 java android loops crash textview

我有 Android 应用程序。我想将一些 TextView 添加到 Fragment 中。但是一开始就崩溃了。 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}

设置 fragment :

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;
        }
    }

我有这个异常(exception):

    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 的方法,一切都很好。问题出在 fragment 的某个地方。*

最佳答案

问题出在 onCreateView 方法中,您在 fragment 父亲 (MainActivity) 中找到 LinearLayout,但您必须在刚刚膨胀的 View 中找到。

替换这一行:

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

通过

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

一切都会好起来的!

关于java - Android 将 TextViews 添加到 fragment 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460190/

相关文章:

c++ - 评估字符串的 bool 函数

java - 每个 Wicket 口 session 都有新 bean

java - 创建带有圆角的表格

android - Google 是否停止支持 Android Eclipse 插件?

android - Android中fillwindow()中的无效语句

java - 循环遍历 InputStream 截断数据

java - 从列表中删除具有空属性的对象的最有效方法

java - 如何在 Vaadin 8 中添加 validator ?

java - 如何使用 Java 转义 XML 中的退格键?

java - findViewById() 在包含的布局上返回 null?