2017-08-09 41 views
-1

在我看來包 創建的RelativeLayout類和膨脹的XML文件中 類使用到的主要活動 但沒有任何錯誤,模擬器已停止如何在Android的RelativeLayout類中充氣XML佈局?

import android.content.Context; 
import android.content.res.AssetManager; 
import android.util.AttributeSet; 
import android.view.LayoutInflater; 
import android.widget.EditText 
import android.widget.RelativeLayout; 
import android.widget.TextView; 

import net.sibdiet.R; 

public class AboutView extends RelativeLayout { 

    private TextView about_txt; 
    private AssetManager assets; 

    public AboutView(Context context) { 
     super(context); 
     initializeViews(context); 
    } 

    public AboutView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initializeViews(context); 
    } 

    private void initializeViews(Context context) { 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     inflater.inflate(R.layout.aboutus_layout, this); 
    } 

    @Override 
    protected void onFinishInflate() { 
     super.onFinishInflate(); 
     about_txt = (EditText) findViewById(R.id.aboutus_txt); 
    } 

    public AssetManager getAssets() { 
     return assets; 
    } 
} 

我需要充氣aboutus_layout.xml

<merge 
    xmlns:android="http://schemas.android.com/apk/res/android"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <TextView 
      android:id="@+id/aboutus_txt" 
      android:layout_width="61dp" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentTop="true" 
      android:layout_marginRight="16dp" 
      android:layout_marginTop="16dp" 
      android:text="@string/about" 
      android:textColor="@color/Green" 
      android:textSize="20sp"/> 

    </RelativeLayout> 
</merge> 

在主要活動中使用自定義視圖 main_activity.xml

<?xml version="1.0" encoding="utf-8"?> 

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#DCDCDC" 
    tools:context="net.sibdiet.MainActivity"> 

    <net.sibdiet.View.AboutView 
     android:id="@+id/about_us_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 

</android.support.constraint.ConstraintLayout> 

blah您的帖子似乎包含未正確格式化爲代碼的代碼。請使用代碼工具欄按鈕或CTRL + K鍵盤快捷鍵將所有代碼縮進4個空格。要獲得更多編輯幫助,請單擊[?]工具欄圖標。

回答

1

你的代碼的問題是:

1)更換LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);LayoutInflater inflater = LayoutInflater.from(getContext())

2)從aboutus_layout.xml刪除RelativeLayout,因爲它是多餘的存在。使您的視圖(AboutView)成爲視圖層次結構的根。