I want to create a custom view which should be added in another custom view.
The second view will be a container, so it should be able to contain the first view as its child.
For creating this views I am extending ViewGroup & LinearLayout classes.
Child view class is NodeView
public class NodeView extends LinearLayout
{
private final static String TAG = "NodeView";
private ImageView ivTop;
private ImageView ivBottom;
private Context myContext;
public NodeView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.myContext = context;
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_test_multi, this, true);
ivTop = (ImageView) getChildAt(0);
ivBottom = (ImageView) getChildAt(2);
ivTop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(myContext, "Top Clicked", Toast.LENGTH_SHORT).show();
}
});
ivBottom.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(myContext, "Bottom Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
}
public NodeView(Context context)
{
this(context, null);
}
}
& the container class is TreeViewGroup
public class TreeViewGroup extends ViewGroup
{
private static final String TAG = "CustomTreeNodeView";
NodeView nodeView;
public TreeViewGroup(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
nodeView = new NodeView(getContext());
addView(nodeView);
}
public TreeViewGroup(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public TreeViewGroup(Context context)
{
this(context, null, 0);
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
}
}
& xml layout for node view is view_test_multi.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_centerVertical="true"
android:src="#drawable/point_grey" />
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_centerVertical="true"
android:src="#drawable/point_red" />
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_centerVertical="true"
android:src="#drawable/point_grey" />
</merge>
My activity's layout is activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.ab1209.testcustom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.ab1209.testcustom.view.TreeViewGroup
android:id="#+id/activity_main_custom_tree_node_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MainActivity class is
**public class MainActivity extends Activity
{
TreeViewGroup treeNodeView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
treeNodeView = (TreeViewGroup) findViewById(R.id.activity_main_custom_tree_node_view);
}
}**
When I run the app I don't see the NodeView added in main View. Am I doing the right thing if not please tell me how can I make it working?
To create a custom ViewGroup, the only method you need to override is
onLayout. The onLayout is triggered after the ViewGroup itself has
finished laying itself out inside its own container ViewGroup and is
now responsible for laying out its children. It should call the layout
method on all of its children to now position and size them (the left
and top parameters will determine the child view’s x and y and the
right and bottom will determine its width (right – left) and height
(top-bottom).
So your TreeViewGroup code will look like :
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) child
.getLayoutParams();
int childLeft = 0;
int childTop = 0;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
int measuredWidth = 200; // Calculate the height
int measuredHeight = 200; // Calculate the width
setMeasuredDimension(measuredWidth, measuredHeight);
}
Refer this link http://arpitonline.com/2012/07/01/creating-custom-layouts-for-android/
Related
In this below code i want to set center_horizontal as attachmentSlidingLayer view id but layout_gravity and gravity for parent and child view doesn't work correctly and by default gravity is left side
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:slidingLayer="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<io.codetail.widget.RevealFrameLayout <!-- extends from FrameLayout -->
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<com.test.libraries.SlidingLayer <!-- extends from BoundedFrameLayout-->
android:id="#+id/attachmentSlidingLayer"
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_gravity="center_horizontal"
android:elevation="5dp"
app:bounded_width="450dp"
android:foregroundGravity="center_horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:background="#drawable/sheet_shadow"
android:orientation="vertical"
app:bounded_width="450dp">
</LinearLayout>
</<com.test.libraries.SlidingLayer.SlidingLayer >
</io.codetail.widget.RevealFrameLayout>
</android.support.design.widget.CoordinatorLayout>
BoundedFrameLayout class:
public class BoundedFrameLayout extends FrameLayout {
private final int mBoundedWidth;
private final int mBoundedHeight;
public BoundedFrameLayout(Context context) {
super(context);
mBoundedWidth = 0;
mBoundedHeight = 0;
}
public BoundedFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoundedView);
mBoundedWidth = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_width, 0);
mBoundedHeight = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_height, 0);
a.recycle();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Adjust width as necessary
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
if (mBoundedWidth > 0 && mBoundedWidth < measuredWidth) {
int measureMode = MeasureSpec.getMode(widthMeasureSpec);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedWidth, measureMode);
}
// Adjust height as necessary
int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
if (mBoundedHeight > 0 && mBoundedHeight < measuredHeight) {
int measureMode = MeasureSpec.getMode(heightMeasureSpec);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedHeight, measureMode);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
RevealFrameLayout class:
public class RevealFrameLayout extends FrameLayout implements RevealAnimator{
private Path mRevealPath;
private final Rect mTargetBounds = new Rect();
private RevealInfo mRevealInfo;
private boolean mRunning;
private float mRadius;
public RevealFrameLayout(Context context) {
this(context, null);
}
public RevealFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RevealFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mRevealPath = new Path();
}
#Override
public void onRevealAnimationStart() {
mRunning = true;
}
#Override
public void onRevealAnimationEnd() {
mRunning = false;
invalidate(mTargetBounds);
}
#Override
public void onRevealAnimationCancel() {
onRevealAnimationEnd();
}
#Override
public void setRevealRadius(float radius){
mRadius = radius;
mRevealInfo.getTarget().getHitRect(mTargetBounds);
invalidate(mTargetBounds);
}
#Override
public float getRevealRadius(){
return mRadius;
}
#Override
public void attachRevealInfo(RevealInfo info) {
mRevealInfo = info;
}
#Override
public SupportAnimator startReverseAnimation() {
if(mRevealInfo != null && mRevealInfo.hasTarget() && !mRunning) {
return ViewAnimationUtils.createCircularReveal(mRevealInfo.getTarget(),
mRevealInfo.centerX, mRevealInfo.centerY,
mRevealInfo.endRadius, mRevealInfo.startRadius);
}
return null;
}
#Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if(mRunning && child == mRevealInfo.getTarget()){
final int state = canvas.save();
mRevealPath.reset();
mRevealPath.addCircle(mRevealInfo.centerX, mRevealInfo.centerY, mRadius, Path.Direction.CW);
canvas.clipPath(mRevealPath);
boolean isInvalided = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(state);
return isInvalided;
}
return super.drawChild(canvas, child, drawingTime);
}
}
I have a created custom layout but it is not working. When I use include the layout instead of set com.samsung.android.app.spage.CustomView.WeatherStateView it is working ok. I found some answers like use the <merge> tag but it not working too, please help me:
weather_state_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/weather_state_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/current_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="current location" />
<include layout="#layout/detail_info_frag_hourly_content" /></LinearLayout>
WeatherStateView.java
public class WeatherStateView extends LinearLayout implements View.OnClickListener{
private static final String TAG = "WeatherStateView";
private TextView mCurrentLocation;
private Context mContext;
public WeatherStateView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WeatherStateView(Context context) {
super(context);
}
public WeatherStateView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context);
}
private void initialize(Context context) {
mContext = context;
LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);
mCurrentLocation = (TextView) findViewById(R.id.current_location);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = MeasureSpec.getSize(heightMeasureSpec);
int size = Math.min(w, h);
setMeasuredDimension(size, size);
}
}
in main_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeatherModule.WeatherViewStateFragment">
<CustomView.WeatherStateView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weather_state_main_layout"
android:orientation="vertical"
/>
You can use something like that
Simply give the cast to the view of included layout and then get it.
View test1View = findViewById(R.id.yourincludedlayoutid);
TextView t1 = (TextView) test1View.findViewById(R.id.emiscode);
Problem here is
LayoutInflater.from(context).inflate(R.layout.weather_state_layout, this);
Should change to ;
ViewGroup viewGroup = (ViewGroup) inflate(mContext , R.layout.weather_state_layout, null); addView(viewGroup);
I am creating a view pager indicator like this image , in which icons scroll to center when clicked , How can I achieve this , I have tried View Pager indicator and tabbed layout but no success .
public class CenteringTabLayout extends TabLayout {
private Typeface mTypeface;
public CenteringTabLayout(Context context) {
super(context);
}
public CenteringTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenteringTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
View firstTab = ((ViewGroup) getChildAt(0)).getChildAt(0);
View lastTab = ((ViewGroup) getChildAt(0)).getChildAt(((ViewGroup) getChildAt(0)).getChildCount() - 1);
if(firstTab!=null)
ViewCompat.setPaddingRelative(getChildAt(0), (getWidth() / 2) - (firstTab.getWidth() / 2), 0, (getWidth() / 2) - (lastTab.getWidth() / 2), 0);
}
#Override
public void addOnTabSelectedListener(#NonNull OnTabSelectedListener listener) {
super.addOnTabSelectedListener(listener);
}
#Override
public void addTab(#NonNull Tab tab) {
super.addTab(tab);
ViewGroup mainView = (ViewGroup) getChildAt(0);
ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
int tabChildCount = tabView.getChildCount();
for (int i = 0; i < tabChildCount; i++) {
View tabViewChild = tabView.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
}
}
}
}
paste this centering tablayout in you java class.
use centering tablayout instead of tablayput in your xml design
I suggest you to use BottomBar
<com.roughike.bottombar.BottomBar
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
app:bb_tabXmlResource="#xml/bottombar_tabs" />
OR
Also check BottomNavigation
<it.sephiroth.android.library.bottomnavigation.BottomNavigation
android:id="#+id/BottomNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:bbn_entries="#menu/bottombar_menu_4items"
app:bbn_scrollEnabled="true"
app:bbn_badgeProvider="#string/bbn_badgeProvider"
app:layout_behavior="#string/bbn_phone_view_behavior" />
I want to place different custom view at a certain position that i set and it will always place on the top-left corners.
I have tried the method using
LayoutParams params = new LayoutParams(v1.getWidth(), v1.getHeight());
params.leftMargin = 100;
params.topMargin = 100;
mView.addView(v1,params);
In this way, the left top corner is disappeared...
Further, can I set a rotation on the inserted custom view as well?
please give me some advice to deal with this question
Here is the detail code,
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_main);
myDraw = (RelativeLayout) findViewById(R.id.myDraw);
Button btnAddRect = (Button) findViewById(R.id.btnAdd);
btnAddRect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v1 = vi.inflate(R.layout.drawbox, null);
mfView = (SingleFingerView) v1.findViewById(R.id.draw);
myDraw.addView(v1);
// myDraw.addView(v1, params);
myDraw.invalidate();
}
});
}
CustomView
public class SingleFingerView extends LinearLayout{
public SingleFingerView(Context context) { this(context, null, 0); }
public SingleFingerView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public SingleFingerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.parseAttr(context, attrs);
View mRoot = View.inflate(context, R.layout.test_image_view, null);
mView = (ImageView) mRoot.findViewById(R.id.view);
mPushView = (ImageView) mRoot.findViewById(R.id.push_view);
mPush1DView = (ImageView) mRoot.findViewById(R.id.push1d_view);
mFirmView = (ImageView) mRoot.findViewById(R.id.firm_view);
mRemoveView = (ImageView) mRoot.findViewById(R.id.remove_view);
addView(mRoot, -1, -1);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setParamsForView(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
xml of Main
<RelativeLayout
android:id="#+id/myDraw"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:src="#drawable/bg"
/>
Try this, no need to make things so complicated.
That should add your custom view to your relativeLayout with the width height you want and a left and top margins of 100px.
public void onClick(View v) {
mfView = new SingleFingerView(MainActivity.this);
RelativeLayout.LayoutParams prms = new RelativeLayout.LayoutParams(width,height);
prms.setMargins(100,100,0,0);
myDraw.addView(mfView,prms);
}
Hope this helps.
What I am trying to achieve:
measure a container View in my layout, mainContainer, that is defined in the XML
pass the mainContainer's width and height to a different custom View before onDraw() is called
I want to pass the width and height so the custom View knows where to draw canvas.drawBitmap using coordinates
The custom view will be programmatically created from code
How can I pass the measured int width and int height to my custom View before onDraw() is called?
Custom View
public class AvatarView extends ImageView {
private Bitmap body;
private Bitmap hat;
public AvatarView(Context context) {
super(context);
init();
}
public AvatarView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AvatarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
body = BitmapFactory.decodeResource(getResources(), R.drawable.battle_run_char);
hat = BitmapFactory.decodeResource(getResources(), R.drawable.red_cartoon_hat);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(body, x, y, null);
canvas.drawBitmap(hat, x, y, null);
}
}
Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customize_avatar, container, false);
final RelativeLayout mainContainer = (RelativeLayout) view.findViewById(R.id.main_container);
TwoWayView inventoryList = (TwoWayView) view.findViewById(R.id.inventory);
inventoryList.setAdapter(null);
inventoryList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
});
mainContainer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
// Retrieve the width and height
containerWidth = mainContainer.getWidth();
containerHeight = mainContainer.getHeight();
// Remove global listener
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
mainContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
mainContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
return view;
}
XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true"
android:background="#fff" >
<com.walintukai.lfdate.CustomTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textStyle="bold"
android:textColor="#fff"
android:textSize="20sp"
android:textAllCaps="true"
android:text="#string/customize_avatar"
android:background="#009BFF" />
<RelativeLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<org.lucasr.twowayview.TwoWayView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/inventory"
style="#style/HorizontalListView"
android:layout_width="match_parent"
android:layout_height="80dp"
android:drawSelectorOnTop="false"
android:background="#f3f3f3" />
</LinearLayout>
What you need to do is add a flag inside your AvatarView that checks if are you going to render this or not in your onDraw method.
sample:
public class AvatarView extends ImageView {
private Bitmap body;
private Bitmap hat;
private int containerHeight;
private int containerWidth;
private boolean isRender = false;
public AvatarView(Context context) {
super(context);
init();
}
public AvatarView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AvatarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setMeasure(int containerWidth, int containerHeight )
{
this.containerHeight = containerHeight;
this.containerWidth = containerWidth;
}
private void init() {
body = BitmapFactory.decodeResource(getResources(), R.drawable.battle_run_char);
hat = BitmapFactory.decodeResource(getResources(), R.drawable.red_cartoon_hat);
}
public void setRender(boolean render)
{
isRender = render;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(isRender )
{
canvas.drawBitmap(body, x, y, null);
canvas.drawBitmap(hat, x, y, null);
}
}
}
Now it wont render when you dont call setRender and set it to true. And just call setMeasure to pass the value.
First you need to call setMeasure and after you set the measure you then call setRender(true) and call invalidate() to call the onDraw method to render the images