Custom View Extending Relative Layout

前端 未结 2 1252
眼角桃花
眼角桃花 2020-12-15 05:13
package com.binod.customviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;

public class CustomView         


        
2条回答
  •  天命终不由人
    2020-12-15 05:50

    You need to have 2 more constructors. To know why

    Do I need all three constructors for an Android custom view?

    public class CustomView extends RelativeLayout{
    
        LayoutInflater mInflater;
        public CustomView(Context context) {
            super(context);
             mInflater = LayoutInflater.from(context);
             init(); 
    
        }
        public CustomView(Context context, AttributeSet attrs, int defStyle)
        {
        super(context, attrs, defStyle);
        mInflater = LayoutInflater.from(context);
        init(); 
        }
        public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mInflater = LayoutInflater.from(context);
        init(); 
        }
       public void init()
       {
           View v = mInflater.inflate(R.layout.custom_view, this, true);
           TextView tv = (TextView) v.findViewById(R.id.textView1);
       tv.setText(" Custom RelativeLayout");
       }
    }
    

    I am posting an example. My packagename is different

    
    
    
    

    custom_view.xml

    
    
    
        
    
    
    

    MainActivity.java

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            }
    }
    

    Snap

    enter image description here

    As pskink suggested there in a RelativeLayout in activity_main.xml with a child CustomView. Then CustomView extends RealtiveLayout and then again you inflate a customview with RelativeLayout and a child TextView. No need for all these. Just a CustomView. Have a TextView created programatically and then add textview to RelativeLayout

    Edit:

    activity_main.xml

    
    

    CustomView

    public class CustomView extends RelativeLayout{
    
        TextView tv;
        public CustomView(Context context) {
            super(context);
             tv = new TextView(context);
             init(); 
    
        }
        public CustomView(Context context, AttributeSet attrs, int defStyle)
        {
        super(context, attrs, defStyle);
        tv = new TextView(context);
        init(); 
        }
        public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        tv = new TextView(context);
        init(); 
        }
       public void init()
       {
           this.addView(tv);
           tv.setText(" Custom RelativeLayout");
       }
    }
    

提交回复
热议问题