android:layout_centerInParent / RelativeLayout - android

i have 3 layers, all of them are RelativeLayouts or based on it:
content-class
overlay-class
infobox-layout
In my code i generate an Overlay-object which inflates a infobox-layout. And then i add the Overlayer to the Content-Layer.
My goal is to center (vertical and horizontal) the Info-box in parent (=overlay) but it doesn't work. It's TOP/LEFT. This is the default behavior, I think.
So here is my code.
I add the Overlayer to the Content-Layer like this:
private void openContent (String url,final ContentLayer content) {
overlay = new Overlay(context, url);
content.addView(overlay);
}
Here is the Overlayer:
public class Overlay extends RelativeLayout {
// some stuff
public Overlay(Context context, String url) {
super(context);
this.context = context;
this.url = url;
init(context, null, -1);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
this.setTag(context.getResources().getString(R.string.overlay));
RelativeLayout.LayoutParams lp = new RelativeLayoutout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
this.setLayoutParams(lp);
this.setBackgroundColor(context.getResources().getColor(R.color.black));
this.getBackground().setAlpha(80);
isMax = getValueInPrefs();
inflateLayout();
}
private void inflateLayout () {
String service = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(service);
inflater.inflate(R.layout.infobox_wrapper, this, true);
}
// some stuff
}
Last but no least, here is my infobox-layout, called infobox_wrapper.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/epaper_webview_wrapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"> <!-- DOESN'T WORK!! -->
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/grau_actionbar">
<Button
android:id="#+id/header_button_close"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="X"
android:layout_alignParentRight="true"
android:layout_margin="5dp"/>
<Button
android:id="#+id/header_button_min_max"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="M"
android:layout_toLeftOf="#id/header_button_close"
android:layout_margin="5dp"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/webview_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grau_actionbar"
android:layout_below="#id/header">
<WebView
android:id="#+id/epaper_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</RelativeLayout>
I am thankful for any help or hint.

I solved the problem like this:
I deleted android:layout_centerInParent="true" in RelativeLayout(#+id/epaper_webview_wrapper) and set it dynamically in openContent-method:
private void openContent (String url,final ContentLayer content) {
overlay = new Overlay(context, url);
RelativeLayout epaper_webview_wrapper= (RelativeLayout)overlay.findViewById(R.id.epaper_webview_wrapper);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)epaper_webview_wrapper.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
epaper_webview_wrapper.setLayoutParams(lp);
content.addView(overlay);
}

Related

RecyclerView grid layout manager doesn't center items

I inherited some big project with a lot of legacy code and now I'm facing some weird stuff..
I need to make this screen have recyclerview with grid layout manager, 2 columns. This is what I get. Is there a way to center those icons in the middle of the screen? I tried with gravity, but nothing works. Maybe there is some thing inside all that legacy code that is making problem or this is just recyclerView's issue?
This is the item's layout (terrible, don't ask..)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/color_view_controller_item_background"
android:orientation="vertical">
<TextView
android:id="#+id/textViewSceneKK"
android:layout_width="match_parent"
android:layout_height="#dimen/room_button_height"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/row_filter_text_margin_left"
android:layout_marginRight="#dimen/row_filter_text_margin_left"
android:gravity="center"
android:shadowDx="-1"
android:shadowDy="-1"
android:shadowRadius="1"
android:textSize="#dimen/row_scene_kk_text_size" />
<TextView
android:id="#+id/textViewSceneName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/row_filter_text_margin_bottom"
android:layout_marginLeft="#dimen/row_filter_text_margin_left"
android:layout_marginRight="#dimen/row_filter_text_margin_left"
android:layout_marginTop="#dimen/row_filter_text_margin_top"
android:clickable="false"
android:gravity="center"
android:longClickable="false"
android:textColor="#color/main_text_color"
android:textSize="#dimen/row_browser_right_name_text_size" />
</LinearLayout>
<!--<View-->
<!--android:id="#+id/filterView"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:clickable="false"-->
<!--android:longClickable="false" />-->
<View
android:id="#+id/filterViewClick"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:selectableItemBackground"
android:focusable="false"
android:focusableInTouchMode="false" />
And fragment't layout:
<customview.CustomRecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none" />
And the code:
customRecyclerView.setHasFixedSize(false);
customRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
customRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
R.drawable.line_separator_empty, DividerItemDecoration.VERTICAL_LIST));
customRecyclerView.setAdapter(adapter);
CustomRecyclerView.java
public class CustomRecyclerView extends RecyclerView {
private boolean enableScroll = true;
public CustomRecyclerView(Context context) {
super(context);
}
public CustomRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isEnableScroll() {
return enableScroll;
}
public void setEnableScroll(boolean enableScroll) {
this.enableScroll = enableScroll;
}
#Override
public int computeVerticalScrollRange() {
return super.computeVerticalScrollRange();
}
#Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (enableScroll) {
return super.onInterceptTouchEvent(e);
}
return false;
}
}
You have to use layout gravity to make it center & need to change match-parent to wrap_content, also you have to assign layout gravity runtime. try this code:
Adapter item layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:id="#+id/top_header_rl"
android:background="#color/app_header_color"
android:orientation="vertical">
<TextView
android:id="#+id/textViewSceneKK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center"
android:shadowDx="-1"
android:shadowDy="-1"
android:shadowRadius="1"
android:text="Heder name"
android:textSize="26sp" />
<TextView
android:id="#+id/textViewSceneName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:clickable="false"
android:gravity="center"
android:text="Footer name"
android:longClickable="false"
android:textSize="25sp" />
</LinearLayout>
<!--<View-->
<!--android:id="#+id/filterView"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:clickable="false"-->
<!--android:longClickable="false" />-->
<View
android:id="#+id/filterViewClick"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?android:selectableItemBackground"
android:focusable="false"
android:focusableInTouchMode="false" />
</FrameLayout>
Adapter Code:
public class CenterGridView extends RecyclerView.Adapter<CenterGridView.CenterGridViewViewHolder> {
private Context context;
public CenterGridView(Context context){
this.context =context;
}
#Override
public CenterGridViewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CenterGridViewViewHolder(LayoutInflater.from(context).inflate(R.layout.new_tiem,parent,false));
}
#Override
public void onBindViewHolder(CenterGridViewViewHolder holder, int position) {
if(position%2==0){
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
holder.top_header_rl.setLayoutParams(params);
}else{
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.LEFT;
holder.top_header_rl.setLayoutParams(params);
}
}
#Override
public int getItemCount() {
return 20;
}
class CenterGridViewViewHolder extends RecyclerView.ViewHolder{
private LinearLayout top_header_rl;
public CenterGridViewViewHolder(View itemView) {
super(itemView);
top_header_rl = (LinearLayout)itemView.findViewById(R.id.top_header_rl);
}
}
}
Main Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<com.demostudies.CustomRecyclerView
android:id="#+id/tests"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></com.demostudies.CustomRecyclerView>
</LinearLayout>
// Set Adapter
CustomRecyclerView customRecyclerView = (CustomRecyclerView)findViewById(R.id.tests);
customRecyclerView.setHasFixedSize(false);
customRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
customRecyclerView.setAdapter(new CenterGridView(this));
try this:
it's working for me
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
>
</androidx.recyclerview.widget.RecyclerView>

Android: How to dynamically add a "Custom View" into a linear layout

I am a newer on building up Android application.
I want to add a new "custom view", which is composed of buttons and imageView, when i click the button in the MainActivity.
I have followed some of the website list below to build a custom view.
javatechig
developer.android.com
They work perfect. However, if i want to dynamically add a custom view with
sView sview = new sView(MainActivity.this);
nothing happen later on...
Or if I want to new a custom view by
sView sview = new sView(MainActivity.this, attrs);
Where can i find and set the attrs????
Here is my Code,
in the MainActivity,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDraw = (RelativeLayout) findViewById(R.id.myDraw);
btnAddRect = (Button) findViewById(R.id.btnAdd);
mfView = (sView) findViewById(R.id.draw);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SingleFingerView sFingerView = new sView(MainActivity.this);
myDraw.addView(sFingerView);
}
});
}
in the Custom View,
public class sView extends LinearLayout{
public sView(Context context) {
this(context, null, 0);
}
public sView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public sView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this._1dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, context.getResources().getDisplayMetrics());
this.parseAttr(context, attrs);
View mRoot = View.inflate(context, R.layout.test_image_view, null);
addView(mRoot, -1, -1);
mView = (ImageView) mRoot.findViewById(R.id.view);
mPushView = (ImageView) mRoot.findViewById(R.id.pview);
mFirmView = (ImageView) mRoot.findViewById(R.id.fview);
mRemoveView = (ImageView) mRoot.findViewById(R.id.rview);
}
private void parseAttr(Context context, AttributeSet attrs) {
if (attrs == null) return;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.sView);
if (a != null) {
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
if (attr == R.styleable.sView_centerInParent) {
this.mCenterInParent = a.getBoolean(attr, true);
} ...
with some attributes set setting
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setParamsForView(widthMeasureSpec, heightMeasureSpec); // some params are set here
}
and the xml file
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:pushtouch="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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" >
<TextView
android:id="#+id/tv_touch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="abc"
android:singleLine="false"
/>
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="ADD IMAGE" />
<RelativeLayout
android:id="#+id/myDraw"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.sView
android:id="#+id/draw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
pushtouch:centerInParent="true"
pushtouch:image="#drawable/image"
pushtouch:image_width="120dp"
pushtouch:image_height="100dp"
pushtouch:push_image="#drawable/p_btn"
pushtouch:push_image_width="50dp"
pushtouch:push_image_height="50dp"
pushtouch:firm_image="#drawable/ok"
pushtouch:firm_image_width="50dp"
pushtouch:firm_image_height="50dp"
pushtouch:remove_image="#drawable/remove"
pushtouch:remove_image_width="50dp"
pushtouch:remove_image_height="50dp"
android:scaleType="centerInside"
android:layout_alignLeft="#id/result"
android:layout_alignTop="#id/result"
android:layout_alignRight="#id/result"
android:layout_alignBottom="#id/result"
/>
</RelativeLayout>
</LinearLayout>
and corresponding view t_view.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/view"
android:layout_width="200dp"
android:layout_height="200dp"
android:focusableInTouchMode="true"
android:focusable="true"/>
<ImageView
android:id="#+id/push_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
/>
<ImageView
android:id="#+id/firm_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
/>
<ImageView
android:id="#+id/remove_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
/>
</FrameLayout>
Use the LayoutInflator to create a view based on your layout template, and then inject it into the view where you need it.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
You may have to adjust the index where you want to insert the view.
Source : Android - Dynamically Add Views into View
u can add some getter and setter function. attrs used in xml.or u can do like this:
test.xml
<com.example.sView
android:id="#+id/draw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
pushtouch:centerInParent="true"
pushtouch:image="#drawable/image"
pushtouch:image_width="120dp"
pushtouch:image_height="100dp"
pushtouch:push_image="#drawable/p_btn"
pushtouch:push_image_width="50dp"
pushtouch:push_image_height="50dp"
pushtouch:firm_image="#drawable/ok"
pushtouch:firm_image_width="50dp"
pushtouch:firm_image_height="50dp"
pushtouch:remove_image="#drawable/remove"
pushtouch:remove_image_width="50dp"
pushtouch:remove_image_height="50dp"
android:scaleType="centerInside"
android:layout_alignLeft="#id/result"
android:layout_alignTop="#id/result"
android:layout_alignRight="#id/result"
android:layout_alignBottom="#id/result"
/>
onclick -> {
View v = getLayoutInflater().inflate(R.layout.a,null);
myDraw.addView(sFingerView);
}

Replaced views in LinearLayout programmatically

I have layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#535353">
<TextView
android:id="#+id/promo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:padding="5dp"
android:layout_weight="1"
/>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:padding="5dp"
android:layout_weight="1"
/>
</LinearLayout>
and I want to replace promo and title. Set first title, then promo.
I use this snippet.
public class AdView extends LinearLayout{
TextView promo;
public AdView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view, this);
promo = (TextView) findViewById(R.id.promo);
title = (TextView) findViewById(R.id.title);
}
private void changePosition() {
removeView(promo);
addView(promo);
}
But, I get error: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
So, could you help me? How can I do this?

Calculate margins from coordinates in android screen

i have a library to insert floating buttons in a layout (http://prolificinteractive.com/blog/2014/07/24/android-floating-action-button-aka-fab/)
Then, i have this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp">
<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="4dp"
android:textSize="45sp"
android:textColor="#737373"
android:id="#+id/faIcon"
fontawesometext:fa_icon="fa-question" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text='"texto de ejemplo de pregunta"'
android:id="#+id/tvQuestion"
android:textColor="#color/primary"
android:textStyle="bold"
android:textSize="28sp"
android:typeface="monospace"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginBottom="16sp" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameConainter"
android:background="#color/dark_grey" />
</LinearLayout>
And i need to set the center of the button in the middle of framelayout top, like as the left image:
I have this in a custom view:
public class YesNoReplyView extends ReplyParentView {
private FloatingActionButton buttonYes;
private FloatingActionButton buttonNo;
public YesNoReplyView(Context context) {
super(context);
}
public YesNoReplyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public YesNoReplyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void initializeComponents() {
int[] position = new int[2];
getLocationOnScreen(position);
buttonYes = new FloatingActionButton.Builder((Activity)getContext())
.withDrawable(getResources().getDrawable(R.drawable.ic_plus))
.withButtonColor(getResources().getColor(R.color.green_success))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 16, 16)
.create();
buttonNo = new FloatingActionButton.Builder((Activity)getContext())
.withDrawable(getResources().getDrawable(R.drawable.ic_plus))
.withButtonColor(getResources().getColor(R.color.primary))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 26, 26)
.create();
}
#Override
public String getResult() {
String result = "";
return result;
}
}
But i dont know how can i calculate the margins from the coordinates to set the view in the position i want..
Anyone knows any way better to do it this?(I cant use a XML layout..)

How to add to the layout compound component programmatically Android?

I created a compound component Box which I want to add to the layout. Box xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayoutForBlock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" android:background="#drawable/screen_background" android:layout_marginLeft="5dp" android:layout_marginTop="5dp">
<ImageButton
android:id="#+id/imageButtonContent"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:scaleType="fitCenter"
android:src="#drawable/beach_bed" android:background="#drawable/buttonbackground" android:clickable="true" android:layout_margin="5dp" android:contentDescription="#string/sample_text"/>
<TextView
android:id="#+id/textViewContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/sample_text"
android:textColor="#color/deep_blue" android:layout_margin="5dp"/>
</LinearLayout>
</merge>
Box class:
public class Box extends LinearLayout {
private TextView textContent;
private ImageView imageContent;
public Box(Context context, AttributeSet attrs) {
super(context, attrs);
((Activity)getContext()).getLayoutInflater().inflate(R.layout.box, this);
setupViewItems();
}
private void setupViewItems() {
textContent = (TextView) findViewById(R.id.textViewContent);
imageContent = (ImageView) findViewById(R.id.imageButtonContent);
}
public void setTextContent(String text) {
this.textContent.setText(text);
}
public void setImageContent(String tag) {
this.imageContent.setContentDescription(tag);
}
}
Everything works if I add the Box to the main xml file like:
<com.mypackage.alexey.Box
android:id="#+id/mybox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
The problem is that I'd like to create many of boxes programmatically something like this: Box mybox= new Box();. How to do it?
I would suggest you also implement the constructors of the LinearLayout that takes only a Context:
public Box(Context context) {
super(context);
}
Then in your Activity, when you want to add a new Box, instantiate the Box class and add it to your layout:
// I assumed you have a LinearLayout to which you want to add your Box
LinearLayout parent = (LinearLayout) findViewById(R.id.parent_id);
//create the Box and added to the parent above
Box theBox = new Box(this); // if you are in an Activity
//some LayoutParams to replicate your xml attributes
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// set the Orientation for the Box
theBox.setOrientation(LinearLayout.HORIZONTAL);
//add the Box
parent.addView(theBox);

Categories

Resources