Home > database >  How to create a customizable and reusable component?
How to create a customizable and reusable component?

Time:10-24

I designed an action bar that has several variations:

enter image description here

As you can see this action bar always has a header and there may be action buttons.

I understand that I can just create five action bars and use them. But I want to create one component and reuse it everywhere in my application.

For example, in ReactJS I would just create one component ActionBar with some properties and reuse it where I need it, such as:

<ActionBar
  isBackButton = true
  text = "Screen name"
  actionButton = "Add"
/>

or

<ActionBar
  isBackButton = false
  text = "Another screen name"
  actionButton = "None"
/>

How do I achieve this? Or should I not get steamed up and just create five different action bars? Or create a universal action bar with text, right and left buttons, and then dynamically customize button icons, text and onClick actions in java code?

I definitely need your advice on what to do.

CodePudding user response:

So the easiest way to do this is with a custom view. You'd create a layout file for it:

toolbar.xml (this is simplifies to just give the basic idea, you need to fill in all the styling data:

  <LinearLayout>
    <ImageView android:id="@ id/back"/>
    <TextView android:id="@ id/text">
    <ImageView android:id="@ id/icon>
  </LinearLayout>

You'd then write a view

ToolbarView.java:

package com.example public class ToolbarView extends View {

private ImageView back;
private TextView text;
private ImageView icon;
public ToolbarView(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.toolbar, this)
    back = findViewById(R.id.back)
    text = findViewById(R.id.text)
    //Same for all other views
}

public void setText(String text) {
   text.setText(text)
}

public void setBackEnabled(boolean enabled) {
   back.setVisibility(enabled ? VISIBLE : GONE)
}

public void setIcon(Drawable icon) {
    if(icon == null) {
        icon.setVisibility(GONE)
     }
     else {
        icon.setVisibility(VISIBLE)
        icon.setDrawable(icon)
     }
} 

After that, you can just put <com.example.Toolbar/> in your other layouts and it will embed the toolbar. You can get it via FindViewById and then call setText, setBackEnabled, etc.

  • Related