Android Layout programmatically - android

layout\layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rR1MessageBubble"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rR2MessageBubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/drawable_sky_background_frame">
</RelativeLayout>
</RelativeLayout>
layout\layout_component.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="50dp"
android:layout_height="50dp"
android:orientation="vertical"
android:background="#drawable/frame">
<TextView
android:id="#+id/txtViewTest"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="Hello!"
android:gravity="center" />
</LinearLayout>
drawable\frame.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#FF07DD43" />
<corners android:bottomRightRadius="3dp"
android:bottomLeftRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp"/>
</shape>
MainActivity.java
![package com.kore.layoutdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* #author ayadav
*
*/
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
RelativeLayout rR2MessageBubble = (RelativeLayout)findViewById(R.id.rR2MessageBubble);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rR2MessageBubble.getLayoutParams();
//View-1
View view1 = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_component, null);
rR2MessageBubble.addView(view1);
//View-2
View view2 = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_component, null);
TextView txtViewTest = (TextView) view2.findViewById(R.id.txtViewTest);
txtViewTest.setText("World");
//params.addRule(RelativeLayout.RIGHT_OF, view1.getId());
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
view2.setLayoutParams(params);
rR2MessageBubble.addView(view2);
}
}
Output
Requirement
All i want to add multiple instances of layout_component.xml in layout_main.xml so instead of negative voting please suggest me the way via i can achieve this...thanks

You have made a small mistake buddy, you are assigning a wrong LayoutParam to the view2.
Replace,
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rR2MessageBubble.getLayoutParams();
with
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,100); //or whatever width, height as per your need.
Hope you understand your mistake.

Probably because you set the text to "World".
TextView txtViewTest = (TextView) view2.findViewById(R.id.txtViewTest);
txtViewTest.setText("World");

Related

How to fit all elements in gridview in the whole display?

I am new in android and want to create a gridview with some elements (element with Text and Image) and was guided by this link https://www.viralandroid.com/2016/04/android-gridview-with-image-and-text.html.
I have a layout for the activity screen:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/home_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid_view_image_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="110dp"
android:numColumns="3"/>
</LinearLayout>
the layout for the gridview with text and image:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android_custom_gridview_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/android_gridview_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="15dp" />
<TextView
android:id="#+id/android_gridview_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="25sp" />
</LinearLayout>
This is my code:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class HomeScreenActivity extends AppCompatActivity {
private GridView androidGridView;
private String[] gridViewString = {
"Anlagenübersicht", "Instandhaltungsaufträge", "Handlungsleitfaden",
"Wiki", "Historie", "Fehlerdatenbank",
"Wartungsprotokoll", "Ersatzteile", "Werkzeugkasten",
"Remotezugriff", "Personal", "Über uns"
} ;
private int[] gridViewImageId = {
R.drawable.icons8_roboter_48, R.drawable.icons8_bestellung_48, R.drawable.icons8_aufgabenliste_48,
R.drawable.icons8_doktorhut_48, R.drawable.icons8_vergangenheit_48, R.drawable.icons8_datenbank_40,
R.drawable.icons8_wartung_48, R.drawable.icons8_ersetzen_48, R.drawable.icons8_werkzeugkasten_48,
R.drawable.icons8_assistent_48, R.drawable.icons8_gruppe_vordergrund_ausgewaehlte_48, R.drawable.icons8_ueber_48,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(HomeScreenActivity.this, gridViewString, gridViewImageId);
androidGridView= (GridView) findViewById(R.id.grid_view_image_text);
androidGridView.setAdapter(adapterViewAndroid);
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int i, long id) {
Toast.makeText(HomeScreenActivity.this, "GridView Item: " + gridViewString[+i], Toast.LENGTH_LONG).show();
}
});
}
}
But my Output is:
But I want that all elements will fill the display in height and with, that there will be no space like you can see here:
Finally, I found a solution from this link:
android How to stretch rows in the gridview to fill screen?
I had to set some attributes for my activity class, and use this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
to determine the height and width.
After that, I had to set the Minimum with and height for my View.
For more informations, I recommend you to check the link above. :)

is there a way to dynamicaly add a widget on top of another widget

i'm trying to create a widget called DecoView dynamicaly every time i press a button.
if i just put two deco views in the XML i can see them both and they both look fine on ontop of the other.
but when i try to add it dynamicly in the code, i only create the first one,
and all the rest just aren't get created
what am i missing here ?
can someone help me with this ?
my mainActivity.java
package com.example.shay_v.dynamicdecoviewexample;
import android.graphics.Color;
import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.hookedonplay.decoviewlib.DecoView;
import com.hookedonplay.decoviewlib.charts.SeriesItem;
import com.hookedonplay.decoviewlib.events.DecoEvent;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button mainMenuButton;
int widgetInteger = 1;
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//pointing to display
mainMenuButton = (Button) findViewById(R.id.button);
mainMenuButton.setOnClickListener(this);
//points to the linear layout in the xml
ll = (LinearLayout)findViewById(R.id.mainMenu_mainLayout);
}
private void createDecoViewWidget (int i) {
//adds params to the linear layout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//deco view widget
DecoView decoViewWidget = new DecoView(this);
//adding to view
decoViewWidget.setId(i);
ll.addView(decoViewWidget, params);
//decoViewWidget.configureAngles((int) (Math.random() * 360) + 1, (int) (Math.random() * 100));
//Create data series track
SeriesItem seriesItem = new SeriesItem.Builder(Color.argb(255, (int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)))
//third controller is end point
.setRange(0, 100, 0)
.setLineWidth(60f)
.setInset(new PointF(120f, 120f))
.build();
int series1Index = decoViewWidget.addSeries(seriesItem);
decoViewWidget.addEvent(new DecoEvent.Builder((float) (Math.random() * 100)).setIndex(series1Index).setDelay(1000).build());
}
//button listener
#Override
public void onClick(View v) {
createDecoViewWidget (widgetInteger);
widgetInteger++;
}
}
my activity_main.xml >
<?xml version="1.0" encoding="utf-8"?>
<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"
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="com.example.shay_v.dynamicdecoviewexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<LinearLayout
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:id="#+id/mainMenu_mainLayout"
android:layout_centerHorizontal="true"></LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
anyone ?
When you are creating the Views they are being added into a LinearLayout. This type of layout will position the views one after the other, so the second view is being drawn off the visible area of the screen.
As you want all views to be drawn on top of each other you should use a RelativeLayout.

Not able to create Custom button in pop up activity

I have made custom buttons before and they work just fine. But something is wrong in this one. It does not take up the drawable I specified . Activity layout file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawable="#drawable/button_continue"
android:id="#+id/continue_button"
android:onClick="goToStart"
android:layout_gravity="center_vertical"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="86dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/dialogue_textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Custom Button(button_continue.xml) :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="#drawable/button_continue_pressed"/>
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="#drawable/button_continue_focused"/>
<item
android:state_enabled="true"
android:drawable="#drawable/button_continue_enabled"/>
</selector>
I don't think that it really has much to do with the activity file but still :
package com.mycompany.whackamole;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import static com.mycompany.whackamole.GameView.*;
public class Pop extends AppCompatActivity{
int width , height ;
TextView textView;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pop_activity);
width = getResources().getDisplayMetrics().widthPixels;
height = getResources().getDisplayMetrics().heightPixels;
getWindow().setLayout(width , (int)(height * 0.5));
textView = (TextView) findViewById(R.id.dialogue_textView);
setScoreText();
intent = getIntent();
}
public void goToStart(View view) {
Intent boo = new Intent(this , StartActivity.class);
startActivity(boo);
}
private void setScoreText() {
textView.setText(String.valueOf("Time's up! Your score was " + score));
}
}
Great if you could help!
In your xml file change:
android:background="#drawable/button_continue"
in place of:
android:drawable="#drawable/button_continue"
It is because you have set the wrong attribute in the layout file. It should be android:background and not drawable.

Android inflating views from other layouts

I'm relatively new to android development and I'm trying to find a way to inflate a view repeatedly each time when a button is pressed, in a different location, so every inflated view has its own position:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class teamCreateScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.team_locate_layout);
}
public void createTeam(View view) {
final RelativeLayout rlTeam = (RelativeLayout) findViewById(R.id.rlTeam);
View teamBox = View.inflate(this, R.layout.team_box, rlTeam);
final TextView teamBoxView = (TextView) findViewById(R.id.team_task_box);
teamBoxView.setX(0);
teamBoxView.setY(230);
}
}
The XML code of the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rlTeam">
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/teamAddBtn"
android:text="+"
android:textSize="30sp"
android:onClick="createTeam"/>
</RelativeLayout>
XML code of the view that's being inflated:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="192dp"
android:layout_height="120dp"
android:id="#+id/team_task_box"
android:text="New Team" />
</RelativeLayout>
I want to use the same view to inflate multiple boxes with different coordinates in the layout. Every time I press the button to inflate the view again it inflates the box in the same coordinates so they overlap. I need to make the second box to appear to the first one's right, the third below 1st and so on, much like a grid of boxes.
Try this code and tell me whether it works. Remove the inflating of layout
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class teamCreateScreen extends Activity {
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.team_locate_layout);
}
public void createTeam(View view) {
final RelativeLayout rlTeam = (RelativeLayout) findViewById(R.id.rlTeam);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(getApplicationContext());
if(tv.getId()>0) {
relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
}
tv.setId(i);
r1Team.addView(tv, relativeParams);
i++;
}
}
Declare int i=0; as a global variable and increment it in the createTeam() method.

Orientation change does not redraw layout completely

This is a Major Edit on my previous question
I'm creating a custom (composite) component named OneLineSeeker that consists of a TextView and a SeekBar.
When I have multiple OneLineSeekers declared in a layout, they don't retain their state on configuration change. All seeker thumbs assume the same position (the position of the last OneLineSeeker) on configuration change.
If I don't use the custom component and use only SeekBars individually (uncomment //a() in main activity), they will retain their individual positions on configuration change.
Can anyone help?
src files
A_seekbarsActivity.java
package com.an;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class A_seekbarsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//a();
}
void a() {
setContentView(R.layout.main_1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SeekBar sb = (SeekBar) findViewById(R.id.seekBar1);
if(sb.getProgress() > 50) sb.setProgress(0);
else sb.incrementProgressBy(5);
}
});
}
}
OneLineSeeker.java
package com.an;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
public class OneLineSeeker extends LinearLayout {
public OneLineSeeker(Context context, AttributeSet attrs) {
super(context, attrs);
View ols = LayoutInflater.from(context).inflate(R.layout.one_line_seeker, this, true);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.OneLineSeeker, 0, 0);
String text = array.getString(R.styleable.OneLineSeeker_name);
if (text != null)
((TextView) ols.findViewById(R.id.name)).setText(text);
array.recycle();
}
}
res/layout files
main_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SeekBar android:id="#+id/seekBar1" android:layout_height="wrap_content" android:layout_width="match_parent"></SeekBar>
<SeekBar android:id="#+id/seekBar2" android:layout_height="wrap_content" android:layout_width="match_parent"></SeekBar>
<SeekBar android:id="#+id/seekBar3" android:layout_height="wrap_content" android:layout_width="match_parent"></SeekBar>
<Button android:text="Button" android:id="#+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:oneLineSeeker="http://schemas.android.com/apk/res/com.an"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.an.OneLineSeeker
android:id="#+id/s1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
oneLineSeeker:name="1"
/>
<com.an.OneLineSeeker
android:id="#+id/s2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
oneLineSeeker:name="2"
/>
<com.an.OneLineSeeker
android:id="#+id/s3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
oneLineSeeker:name='3'
/>
</LinearLayout>
one_line_seeker.xml
<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id='#+id/name'
android:text='name'
/>
<SeekBar
android:id='#+id/seekbar'
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</merge>
res/values files
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="OneLineSeeker">
<attr name="name" format="string"/>
</declare-styleable>
</resources>
Its not supposed to reset its position to zero. This is actually a feature. When view has id associated with, it usually saves and the restores its state on configuration changes.
If you don't want specific view to save state on configuration change, you can remove android:id from view's entry in layout (but you won't be able to control that view then). Another alternative is to extend ProgressBar and disable its ability to restore state.
The last one option is the easiest one: override onRestoreInstanceState() and reset state there:
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
bar.setProgress(0);
}
But I would strongly recommend not resetting view state. After all the whole idea of restoring state on configuration change is to make user think as if nothing really changed. And you need to have very strong reasons to disable this behavior.
In that u have to define Orientation Change Methods.....
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onCreate(null);
}
Try this Code may u get any Help.....

Categories

Resources