Search code examples
androidandroid-layoutandroid-custom-view

android - Getting the handle for child views from custom layout


I have create a Java class extending LinearLayout as shown below

         public class CustomLinear extends LinearLayout{

        Context context;

         public CustomLinear(Context context) {
        super(context);
          this.context=context;

         ViewFlipper viewFlipper=new ViewFlipper(context);
         viewFlipper.setLayoutParams(this.getLayoutParams());
        this.addView(viewFlipper);

        }

And included the custom built layout into my Main.xml as shown below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">



              <com.homevito.customlayout.CustomLinear
            android:id="@+id/one"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:background="@drawable/alerts"
            android:orientation="horizontal" />


</LinearLayout>

And in my MainActivity i'm using main.xml as content view as follows:

     public class MainActivity extends Activity {



         /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
            setContentView(R.layout.main);


        }
    }

I want to handle the viewFlipper from the MainActivity. I tried setting Id for viewFlipper but still dint help...

How can I get to handle the viewflipper.. Thanks in advance


Solution

  • First of all, if you use your custom component in a xml layout you'll need the second constructor implemented(the one that takes a Context, AttributeSet). Second of all you could add a getter method for your ViewFlipper:

    public class CustomLinear extends LinearLayout{
    
            Context context;
            private ViewFlipper mFlipper;
    
            public CustomLinear(Context context, AttributeSet attrs) {
                 super(context, attrs);
                 this.context=context;
                 mFlipper = new ViewFlipper(context);
                 mFlipper.setLayoutParams(this.getLayoutParams());
                 this.addView(mFlipper);
            }
    
          // the getter method
          public ViewFlipper getTheFlipper() {
               return mFlipper;
          }
    

    Then in your activity you could simple do:

    setContentView(R.layout.main);
    CustomLinear cl = (CustomLinear) findViewById(R.id.one);
    ViewFlipper flipperReference = cl.getTheFlipper();