通过膨胀布局来创建自定义视图?

nba*_*lle 86 xml android view

我正在尝试创建一个自定义视图,它将取代我在多个地方使用的某个布局,但我正在努力这样做.

基本上,我想替换这个:

<RelativeLayout
 android:id="@+id/dolphinLine"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
    android:layout_centerInParent="true"
 android:background="@drawable/background_box_light_blue"
 android:padding="10dip"
 android:layout_margin="10dip">
  <TextView
   android:id="@+id/dolphinTitle"
   android:layout_width="200dip"
   android:layout_height="100dip"
   android:layout_alignParentLeft="true"
   android:layout_marginLeft="10dip"
   android:text="@string/my_title"
   android:textSize="30dip"
   android:textStyle="bold"
   android:textColor="#2E4C71"
   android:gravity="center"/>
  <Button
   android:id="@+id/dolphinMinusButton"
   android:layout_width="100dip"
   android:layout_height="100dip"
   android:layout_toRightOf="@+id/dolphinTitle"
   android:layout_marginLeft="30dip"
   android:text="@string/minus_button"
   android:textSize="70dip"
   android:textStyle="bold"
   android:gravity="center"
   android:layout_marginTop="1dip"
   android:background="@drawable/button_blue_square_selector"
   android:textColor="#FFFFFF"
   android:onClick="onClick"/>
  <TextView
   android:id="@+id/dolphinValue"
   android:layout_width="100dip"
   android:layout_height="100dip"
   android:layout_marginLeft="15dip"
   android:background="@android:drawable/editbox_background"
   android:layout_toRightOf="@+id/dolphinMinusButton"
   android:text="0"
   android:textColor="#2E4C71"
   android:textSize="50dip"
   android:gravity="center"
   android:textStyle="bold"
   android:inputType="none"/>
  <Button
   android:id="@+id/dolphinPlusButton"
   android:layout_width="100dip"
   android:layout_height="100dip"
   android:layout_toRightOf="@+id/dolphinValue"
   android:layout_marginLeft="15dip"
   android:text="@string/plus_button"
   android:textSize="70dip"
   android:textStyle="bold"
   android:gravity="center"
   android:layout_marginTop="1dip"
   android:background="@drawable/button_blue_square_selector"
   android:textColor="#FFFFFF"
   android:onClick="onClick"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

这样:

<view class="com.example.MyQuantityBox"
    android:id="@+id/dolphinBox"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:myCustomAttribute="@string/my_title"/>
Run Code Online (Sandbox Code Playgroud)

所以,我不想要一个自定义布局,我想要一个自定义视图(这个视图不应该有子视图).

唯一可以从MyQuantityBox的一个实例改为另一个实例的是标题.我非常希望能够在XML中指定它(就像我在最后的XML行上那样)

我怎样才能做到这一点?我应该将RelativeLayout放在/ res/layout中的XML文件中并在MyBoxQuantity类中对其进行充气吗?如果是,我该怎么办?

谢谢!

Fox*_*Fox 109

有点旧,但我想分享我是怎么做的,基于chubbsondubs的回答:我使用FrameLayout(参见文档),因为它用于包含单个视图,并从xml中向其充气.

代码如下:

public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public MyView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        View view = inflate(getContext(), R.layout.my_view_layout, null);
        addView(view);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 由于View类具有静态inflate()方法,因此不需要LayoutInflater.from() (9认同)
  • 这不只是 Johannes 的解决方案:http://stackoverflow.com/questions/17836695/android-custom-view-from-inflated-layout 尽管如此,这会增加另一个布局。所以这不是我猜的最好的解决方案。 (2认同)
  • 它是,但约翰内斯的解决方案是从7.24.13开始的,并且思维来自7.1.13 ...而且,我的解决方案使用了FrameLayout,它应该只包含一个View(如解决方案中引用的文档中所述).实际上它意味着用作View的占位符.我不知道任何解决方案不使用占位符为膨胀的视图进行调用. (2认同)

chu*_*ubs 24

是的,你可以这样做.RelativeLayout,LinearLayout等是Views,因此自定义布局是自定义视图.只需考虑一下,因为如果你想创建一个自定义布局,你可以.

你想要做的是创建一个复合控件.您将创建RelativeLayout的子类,在代码中添加所有组件(TextView等),在构造函数中,您可以读取从XML传入的属性.然后,您可以将该属性传递给标题TextView.

http://developer.android.com/guide/topics/ui/custom-components.html


Tsu*_*aze 12

使用布局inflater,如下所示

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }
Run Code Online (Sandbox Code Playgroud)


Pha*_*inh 8

这是一个简单的演示,通过从xml扩展来创建customview(compoundview)

attrs.xml

<resources>

    <declare-styleable name="CustomView">
        <attr format="string" name="text"/>
        <attr format="reference" name="image"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        ConstraintLayout(context, attrs, defStyleAttr) {

    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        View.inflate(context, R.layout.custom_layout, this)

        val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        try {
            val text = ta.getString(R.styleable.CustomView_text)
            val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
            if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
            }
            text_title.text = text
        } finally {
            ta.recycle()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

custom_layout.xml

我们应该merge在这里使用而不是ConstraintLayout因为

如果ConstraintLayout在这里使用,布局层次结构将是ConstraintLayout-> ConstraintLayout-> ImageView+ TextView=>我们有1个冗余ConstraintLayout=>对性能不是很好

<?xml version="1.0" encoding="utf-8"?>
<merge 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"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="ContentDescription"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@id/image_thumb"
        app:layout_constraintStart_toStartOf="@id/image_thumb"
        app:layout_constraintTop_toBottomOf="@id/image_thumb"
        tools:text="Text" />

</merge>
Run Code Online (Sandbox Code Playgroud)

使用 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f00"
        app:image="@drawable/ic_android"
        app:text="Android" />

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        app:image="@drawable/ic_adb"
        app:text="ADB" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

结果

在此处输入图片说明

Github演示

  • 这应该是该线程中已接受或投票最多的答案,因为它提到了不必要的布局层次结构。 (9认同)
  • 感谢您提到 `tools:parentTag`,即使经过 9 年的 Android 开发我也不知道❤️ (5认同)
  • 很好的答案,谢谢。对于那些喜欢使用视图绑定的人:`CustomViewBinding.bind(View.inflate(context, R.layout.custom_layout, this))` (2认同)

Nei*_*end 7

在实践中,我发现你需要小心一点,特别是如果你反复使用一点xml.例如,假设您有一个表,您希望为列表中的每个条目创建一个表行.你已经设置了一些xml:

my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>
Run Code Online (Sandbox Code Playgroud)

然后你想用一些代码每行创建一次.它假设您已定义父TableLayout myTable以将行附加到.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}
Run Code Online (Sandbox Code Playgroud)

有关处理rowButton.setOnClickListener(this)的简单示例,请参阅Onclicklistener以获取以编程方式创建的按钮.