Composit widget - what is the preffered way?
Posted
by
Aleksander Gralak
on Stack Overflow
See other posts from Stack Overflow
or by Aleksander Gralak
Published on 2012-12-10T10:25:58Z
Indexed on
2012/12/10
11:06 UTC
Read the original article
Hit count: 491
I want to build reusable widget. It should be ordinal composite of standard elements. What is the best approach. Below is the code sample which I use currently, however there might be something more elegant. Furthermore the sample below runs perfectly in runtime, but visual editor in Eclipse is throwing exceptions (which is not a problem for me at this time). Is there any recommended way of creating composites? Should I use fragment?
public class MyComposite extends LinearLayout {
private ImageView m_a1;
private ImageView m_a2;
private ImageView m_w1;
private ImageView m_w2;
private ImageView m_w3;
private ImageView m_w4;
public CallBackSlider(final Context context) {
this(context, null);
}
public CallBackSlider(final Context context, final AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.my_composite, this, true);
setupViewItems();
}
private void setupViewItems() {
m_a1 = (ImageView) findViewById(R.id.A1Img);
m_w1 = (ImageView) findViewById(R.id.Wave1Img);
m_w2 = (ImageView) findViewById(R.id.Wave2Img);
m_w3 = (ImageView) findViewById(R.id.Wave3Img);
m_w4 = (ImageView) findViewById(R.id.Wave4Img);
m_a2 = (ImageView) findViewById(R.id.A2Img);
resetView();
}
private void resetView() {
m_w1.setAlpha(0);
m_w2.setAlpha(0);
m_w3.setAlpha(0);
m_w4.setAlpha(0);
}
}
Layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyComposite"
... >
<ImageView
android:id="@+id/A1Img"
android:src="@drawable/a1"
...
/>
<ImageView
android:id="@+id/Wave1Img"
...
android:src="@drawable/wave1" />
<ImageView
android:id="@+id/Wave2Img"
...
android:src="@drawable/wave2" />
<ImageView
android:id="@+id/Wave3Img"
...
android:src="@drawable/wave3" />
<ImageView
android:id="@+id/Wave4Img"
...
android:src="@drawable/wave4" />
<ImageView
android:id="@+id/EarImg"
...
android:src="@drawable/a2" />
</LinearLayout>
Then you can use it in other layouts like this:
...
<your.package.MyComposite
android:id="@+id/mc1"
...
/>
...
And use from java code as well as instance of MyComposite class.
© Stack Overflow or respective owner