如何动态地将LinearLayoutCompat视图添加到现有xml布局?

时间:2017-06-04 14:52:05

标签: java android xml android-layout layout-inflater

我有一个包含Texts的数据库。我的活动在顶部有一个TextView(这应该始终保持完整),而在下面我有一个RelativeLayout,它将是我的容器。在我的代码中,只要活动(我将动态插入视图)启动,我就创建一个LinearLayoutCompact对象并设置一些属性。然后我将光标处理到表数据,我为每个数据库元素创建一个TextView,并将其添加到LinearLayoutCompat对象。最后,我尝试将此对象添加到应用程序崩溃的RelativeLayout容器中。我正在使用LayoutInflater并将RelativeLayout容器视为ViewGroup(我在做了一些研究后发现了这种方式)。但是,如果我只是在LinearLayoutCompat对象上使用setContentView它工作正常,但也替换了我想要出现的TextView。以下是我认为必要的文件:

veg_option.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="vertical">

    <TextView             <!-- The one I want intact throughout -->
        android:id="@+id/narrowText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Let's narrow down now !"
        android:textSize="20sp"
        android:textColor="@color/wineBrown"
        android:gravity="center"
        android:padding="10dp"
        android:layout_marginTop="30dp"
        android:elevation="4dp"/>
   <RelativeLayout               <!-- Trying to use this as container -->
        android:id="@+id/dataCont"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

    </RelativeLayout>

</LinearLayout>

VegOptions.java (应该发生所有行动的活动)

package com.techpappy.whattoeat;

/**
 * Created by Mehul on 31-05-2017.
 */

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class VegOptions extends AppCompatActivity{

    protected DBSource vegDBSource;
    private Cursor cursor;
    protected ArrayList<String> mTypes;
    LayoutInflater li = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = li.inflate(R.layout.veg_option, null);
    ViewGroup dataConPt = (ViewGroup) findViewById(R.id.dataCont);

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.veg_option);   
        vegDBSource = new DBSource(VegOptions.this);
        disp();
    }

    private void disp()
    {
        vegDBSource.open();
        cursor = vegDBSource.getInfo();
        LinearLayoutCompat linearLayoutCompat = defaultPage(cursor);
       //setContentView(linearLayoutCompat);  Works fine but replaces all
        dataConPt.addView(linearLayoutCompat);
    }
//Here my LinearLayoutCompat object is prepared and returned
    public LinearLayoutCompat defaultPage(Cursor mCursor) {
        LinearLayoutCompat layout = new LinearLayoutCompat(this);
        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(params);
        layout.setGravity(Gravity.CENTER);
        layout.setOrientation(LinearLayoutCompat.VERTICAL);
        mCursor.moveToFirst();  //Each iteration adds one TextView
        do {
            AppCompatTextView defaultText = new AppCompatTextView(this);
            defaultText.setText(mCursor.getString(mCursor.getColumnIndex(DataBaseHelper.COLUMN_TYPES)));
            defaultText.setTextAppearance(getApplicationContext(), R.style.TextFontMain);
            defaultText.setTextSize(30);
            defaultText.setPadding(0,30,0,30);
            final String temp = (String) defaultText.getText();
            defaultText.setGravity(Gravity.CENTER);
            defaultText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                     Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
                }
            });
            layout.addView(defaultText);
            mCursor.moveToNext();
        }  while(mCursor.isAfterLast() == false);
        return layout;  //LinearLayoutCompat containing all Texts returned
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vegDBSource.close();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }
}

我先前的问题已被低估,但这次我做了大量的研究并找到了正确的方法,但我不能在我的独特案例中使用它

栈跟踪

6-05 19:32:17.679 3450-3450/com.techpappy.whattoeat E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.techpappy.whattoeat, PID: 3450
                                                                       java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.techpappy.whattoeat/com.techpappy.whattoeat.VegOptions}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                           at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
                                                                           at com.techpappy.whattoeat.VegOptions.<init>(VegOptions.java:33)
                                                                           at java.lang.Class.newInstance(Native Method)
                                                                           at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                           at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                           at android.os.Looper.loop(Looper.java:154) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                           at java.lang.reflect.Method.invoke(Native Method) 

1 个答案:

答案 0 :(得分:0)

只需在onCreate()方法中初始化LayoutInflator,View和ViewGroup,问题就解决了。