Android Adding Buttons to Toolbar Programmatically - java

I am trying to create a toolbar programmatically and add left and right bar buttons without using XML.
But the button is not getting aligned to right.
Toolbar TopTulBarVar = new Toolbar(this);
TopTulBarVar.setId(View.generateViewId());
TopTulBarVar.setBackgroundColor(Color.parseColor("#DDDDDD"));
TopTulBarVar.setTitle("Ttl Txt");
TopTulBarVar.setSubtitle("Dtl Txt");
Button NamBarBtnVar = new Button(this);
NamBarBtnVar.setText("Select");
NamBarBtnVar.setBackgroundColor(Color.GREEN);
LinearLayout.LayoutParams NamBarBtnRulVar = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
NamBarBtnRulVar.gravity = Gravity.RIGHT;
TopTulBarVar.addView(NamBarBtnVar, NamBarBtnRulVar);
Also tried
RelativeLayout.LayoutParams RloRulVar = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RloRulVar.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
I am getting as below image
But need like

In Activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar t = (Toolbar) findViewById(R.id.tool);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//left side button
Button b = new Button(this);
Toolbar.LayoutParams l1=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l1.gravity = Gravity.START;
b.setLayoutParams(l1);
b.setText("left");
t.addView(b);
//center Textview
TextView text=new TextView(this);
text.setText("Text:1");
Toolbar.LayoutParams l2 = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l2.gravity = Gravity.CENTER;
text.setLayoutParams(l2);
t.addView(text);
//Right side button
Button b1=new Button(this);
b1.setText("Right");
Toolbar.LayoutParams l3=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l3.gravity=Gravity.END;
b1.setLayoutParams(l3);
t.addView(b1);
}
Toolbar XML code
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:id="#+id/tool"
app:contentInsetLeft="0dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
OUTPUT

For anyone struggling with this nowadays: please make sure to use androidx.appcompat.widget.Toolbar.LayoutParams while adding view programmatically as for me just typing Toolbar.LayoutParams were accidentally resolved to android.widget.Toolbar.LayoutParams by Android Studio. I spent some time trying to figure out why gravity is not changed: no exception occures if set wrond layoutParams before adding a view to the toolbar. I have androidx.appcompat.widget.Toolbar in my layout.

for me I added one switch button in Toolbar and it does work :
<Toolbar
android:id="#+id/toolbar"
style="#style/Toolbar"
android:visibility="visible"
android:background="#color/white">
<Switch
android:id="#+id/btn_accessible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:layout_weight="1"
android:visibility="visible"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textColor="#color/white"
android:textSize="12sp"
android:thumb="#drawable/custom_switch_thumb"
android:track="#drawable/custom_switch_track"
/>
</Toolbar>
and in activity i just set onClick listener

Related

TextView and ImageView stuck out of LinearLayout

I'm building an android app with a TextView, a ScrollView and a LinearLayout, I want to add one TextView and an ImageView to this LinearLayout using Java but they both stay outside of the Layout.
This is my activity XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/galaxy"
tools:context=".Planet">
<TextView
android:id="#+id/planets"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/purple"
android:text="#string/planets"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.05" />
<ScrollView
android:id="#+id/scroll"
android:layout_width="409dp"
android:layout_height="646dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is the code I'm using to generate and add the TextView and the ImageView:
public class MainActivity extends AppCompatActivity {
private ArrayList<Planet> planets = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Planet mercury = Planet.getPlanetFromResources(0, getResources());
planets.add(mercury);
addPlanetToUI(mercury);
}
public void addPlanetToUI(final Planet planet){
int color = getResources().getColor(R.color.yellow);
LinearLayout linear = findViewById(R.id.linear);
linear.setOrientation(LinearLayout.VERTICAL);
linear.setWeightSum(20f);
LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lp1 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lp2 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout horizontal = new LinearLayout(this);
horizontal.setWeightSum(6f);
horizontal.setOrientation(LinearLayout.HORIZONTAL);
lp.weight = 10f;
horizontal.setLayoutParams(lp);
ImageView iv = new ImageView(this);
lp1.weight = .75f;
iv.setImageDrawable(getDrawable(planet.getImgSmallResourceValues()));
iv.setLayoutParams(lp1);
TextView tv = new TextView(this);
lp2.weight= .5f;
tv.setText(planet.getName());
tv.setBackgroundColor(color);
tv.setTextSize(40);
tv.setLayoutParams(lp2);
horizontal.addView(iv);
horizontal.addView(tv);
linear.addView(horizontal);
}
}
This is the outcome:
So is not that your elements are outside of the layout. The problem is that your ScrollView has a top constraint to the top of parent.
Change your ScrollView top constraint (app:layout_constraintTop_toTopOf="parent") to:
app:layout_constraintTop_toBottomOf="#id/planets"
Since your layout container is a ConstraintLayout elements can overlap between them.

Programmatic Toolbar

In my Android assignment we have to create a simple App using only Java and not design view. I want to add icons and text to the toolbar. I can get it to work using design view but I cannot get it to work using Java.
Please advice me if my idea is right. For example to add a button to the toolbar, I create a
android.widget.Button button = new android.widget.Button()
and then add the button to the Toolbar.
My onCreate() function is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
relative_layout = new RelativeLayout(this);
relative_layout.setBackgroundColor(Color.WHITE);
Toolbar tool_bar = new Toolbar(this);
tool_bar.setTitle("Hello");
tool_bar.setBackgroundColor(Color.RED); // actual one I read from R.color.xyz
tool_bar.setTitleTextColor(Color.WHITE);
tool_bar.setId(1);
// tool_bar.setNavigationIcon(R.drawable.ic_launcher_foreground);
tool_bar.setPopupTheme(R.style.Theme_AppCompat_Dialog);
this.setVisible(true);
this.setSupportActionBar(tool_bar);
RelativeLayout.LayoutParams toolbar_layout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
toolbar_layout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
toolbar_layout.addRule(RelativeLayout.CENTER_HORIZONTAL);
Button button = new Button(this);
button.setBackgroundColor(Color.GREEN);
button.setText("Button");
button.setId(2);
RelativeLayout.LayoutParams button_layout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
button_layout.addRule(RelativeLayout.CENTER_HORIZONTAL);
button_layout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// button_layout.setMargins(400, 0, 0, 0);
tool_bar.addView(button, button_layout);
relative_layout.addView(tool_bar, toolbar_layout);
this.setContentView(relative_layout);
}
1) I would like to confirm is this is correct way of doing this?
2) I cannot move the button to the right of the screen as shown in the picture, although I used
RelativeLayout.ALIGN_PARENT_RIGHT
How can we set the alignment to the right?
Your Toolbar will look like this after adding this code :
Use this code to crate your toolbar activity.xml Code :
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Activity.java Code :
Toolbar toolbarTop;
Call setToolbar() inside from your onCreate()
private void setToolbar() {
toolbarTop = (Toolbar) findViewById(R.id.toolbarAdjustScan);
setSupportActionBar(toolbarTop);
TextView search = (TextView)toolbarTop.findViewById(R.id.searchAdjustBtn);
TextView titleToolbar = (TextView)toolbarTop.findViewById(R.id.titleToolbar);
titleToolbar.setText("TakeInventory");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(0);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), TakeInventoryResult.class);
// Bundle args = new Bundle();
// args.putSerializable("ARRAYLIST",(Serializable)inList);
// intent.putExtra("BUNDLE",args);
startActivity(intent);
finish();
}
});
}
The toolbar is just a ViewGroup. So just as you add views to any ViewGroup programmatically, do the same treatment for the toolbar.
Button bt = new Button(this);
bt.setText("Button");
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.FILL_PARENT);
params.gravity = Gravity.RIGHT;
button.setLayoutParams(params);
toolbar.addView(bt);
Happy to help :)

Aligning textview through android java

At the moment everything is done through the java code. I'm creating a relative layout then adding my GL surface view and some text views to it. the problem is I cant align one text view to the top left and the other to the top right. Whats wrong with my code. Also is there a more efficient way of doing this such as doing this through XML instead. Cause I've tried this and it didn't work.
r1 = new RelativeLayout(this);
view = new MyGLSurfaceView(this);
view.setKeepScreenOn(true);//keeps activity from going to sleep
r1.addView(view);
TextView text1 = new TextView(this);
TextView text2 = new TextView(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 50);
RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 200);
lp.addRule(RelativeLayout.ALIGN_RIGHT);
text1.setLayoutParams(lp);
text1.setText("3 Star");
text1.setBackgroundColor(0x4060ff70);
rp.addRule(RelativeLayout.ALIGN_LEFT);
text2.setLayoutParams(rp);
text2.setText("4 Star");
text1.setTextSize(30);
text2.setTextSize(30);
//text2.setBackgroundColor(0x4060ff70);
r1.addView(text1);
r1.addView(text2);
setContentView(r1);
This can be done in XML like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left" />
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right" />
</RelativeLayout>

Programmatically RelativeLayout.ALIGN_RIGHT with a given View.getId() not working

i try to align a TextView programmatically to the right/bottom edge of a button.
However, this static xml code is working:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView10"
android:layout_alignRight="#+id/button"
android:layout_alignBottom="#+id/button" />
</RelativeLayout>
If i try to do it by code, it is not working.
The TextView is getting aligned top/left as it is by default.
The RelativeLayout.ALIGN_RIGHT and ALIGN_BOTTOM seems to be ignored...
// Adding the LinearLayout
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
final LinearLayout.LayoutParams LLParamsCont = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, Utils.dpToPx(getContext(), 50));
// Adding the RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(getContext());
relativeLayout.setLayoutParams(LLParamsCont);
// Adding the Button
Button button = new Button(getContext());
button.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(button)
// Adding the TextView
TextView textView = new TextView(getContext());
textView.setGravity(Gravity.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
Utils.dpToPx(getContext(), 20),
Utils.dpToPx(getContext(), 20));
layoutParams.addRule(RelativeLayout.ALIGN_RIGHT, button.getId()); // <== THIS DOESN'T SEEM TO WORK
layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, button.getId()); // <== THIS DOESN'T SEEM TO WORK
textView.setLayoutParams(layoutParams);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundResource(R.drawable.score_count);
relativeLayout.addView(textView);
linearLayout.addView(relativeLayout)
The TextView is just not beeing aligned to the right/bottom line of the Button.
Does anyone has an idea why that is not working by code, but with static xml?
What did i miss?
Thank you!
With best regards,
Juergen
Try to set a unique id to the Button before create the rule (more info here).
Button button = new Button(getContext());
button.setId(View.generateViewId()); //this utility method is API 17!
I found the solution at this post:
How to lay out Views in RelativeLayout programmatically?
I need to set an id with setId(int) to the Button, then it is working.

How to set all elements of linear layout to be same width in android?

In my android app, I want to create a linear layout of 1 row and 3 columns. Then in each cell, add a new linear layout with 1 column and 2 rows.
Currently it does that, but the width of each of the three cells are wrapping the content, so the overall width of the main linear layout is smaller than the screen width. I want it to match the screen width and then horizontally center the contents of the content of each of the three cells.
Does anyone know how to fix this?
Thanks
This is the code I have
LinearLayout layout = new LinearLayout(this);
layout.setWeightSum(1);
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// ---------
LinearLayout Celllayout = new LinearLayout(this);
Celllayout.setOrientation(LinearLayout.VERTICAL);
Celllayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
TextView titleView = new TextView(this);
titleView.setLayoutParams(lparams);
titleView.setText("Use This");
RadioButton useMapRadio = new RadioButton(this);
Celllayout.addView(titleView);
Celllayout.addView(useMapRadio);
layout.addView(Celllayout);
// ---------
Celllayout = new LinearLayout(this);
Celllayout.setOrientation(LinearLayout.VERTICAL);
Celllayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
titleView = new TextView(this);
titleView.setLayoutParams(lparams);
titleView.setText(date);
ImageButton imagebutton = new ImageButton(this);
imagebutton.setImageResource(R.drawable.calendar);
imagebutton.setBackgroundResource(0);
Celllayout.addView(titleView);
Celllayout.addView(imagebutton);
layout.addView(Celllayout);
// ---------
Celllayout = new LinearLayout(this);
Celllayout.setOrientation(LinearLayout.VERTICAL);
Celllayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
titleView = new TextView(this);
titleView.setLayoutParams(lparams);
titleView.setText("Delete");
imagebutton = new ImageButton(this);
imagebutton.setImageResource(R.drawable.x);
imagebutton.setBackgroundResource(0);
Celllayout.addView(titleView);
Celllayout.addView(imagebutton);
layout.addView(Celllayout);
// ---------
linearlayout.addView(layout);
This is 3 textView in horizontal layout, the main idea is : width of all items in
row must be ==0, and weigth for all items must be the same
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/start_training"
android:textColor="#84d9f4"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/upd_params"
android:textColor="#84d9f4"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="df"
/>
</LinearLayout>
Use Styles, it works like CSS :: Styles in Android
And yeah, it would be better to make layout's in XML

Categories