动态添加按钮到我的工具栏中的linearlayout会产生一种奇怪的方式: 看起来在我的代码中创建并传递给我的视图的按钮的宽度具有随机宽度。我已将layoutparams设置为"包装内容"但它没有任何区别。有关如何解决它的任何线索?我喜欢我的按钮以适应它们包含的文字,而不是更大也不小。
Toolbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="@color/Blue"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout
android:id="@+id/layout_toolbar"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent">
<Button
android:id="@+id/app_name_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="3dp"
android:background="@android:color/transparent"
android:textColor="@android:color/white"
android:textSize="14dp"
android:textStyle="bold"
android:gravity="left|center_vertical"
android:text="@string/app_name" />
<!-- dynamically button will be here-->
</LinearLayout>
</android.support.v7.widget.Toolbar>`
添加按钮的代码:
var layout_toolbar = FindViewById<LinearLayout>(Resource.Id.layout_toolbar);
//Add arrow image
ImageView arrow = new ImageView(context);
arrow.SetBackgroundResource(Resource.Drawable.arrow);
arrow.Id = ariane_lvl_count;
layout_toolbar.AddView(arrow);
//set layoutparams for arrow image
LinearLayout.LayoutParams lp_arrow = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
lp_arrow.Gravity = GravityFlags.Left|GravityFlags.CenterVertical;
lp_arrow.LayoutParameters = lp_arrow;
//Add button
Button btn = new Button(this);
btn.Id = ariane_lvl_count;
btn.TextSize = 15;
var folder = (currentFolder + gridViewString[e.Position] + "/");
btn.Hint = folder;
btn.Text = gridViewString[e.Position];
btn.SetBackgroundColor(Color.Yellow);
btn.SetSingleLine(true);
btn.SetTextColor(Resources.GetColor(Color.Yellow));
layout_toolbar.AddView(btn);
//set layoutparams for button
LinearLayout.LayoutParams lp_btn = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.FillParent);
lp_btn.Gravity = GravityFlags.Left|GravityFlags.CenterVertical;
btn.LayoutParameters = lp_btn;
以红色加下划线的元素占用太多空间,并且不像其他人那样适合文本
答案 0 :(得分:0)
我对你有个想法。为什么不尝试创建样本布局(例如:按钮布局)并使用layoutInflater将其加载到工具栏中。或者在工具栏中创建一个weightSum。
Understanding Android LayoutInflater Understanding Android weightSum