Zap*_*ica 0 android button android-layout
我有以下按钮
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="5dp"
android:textSize="10sp"
android:text="Button" />
Run Code Online (Sandbox Code Playgroud)
现在在我的代码中,我想以编程方式根据某些因素制作动态数量的这些按钮.
现在我花了相当多的时间来尝试使用以下代码:
Button txtName = new Button(getActivity(), null, android.R.attr.buttonStyleSmall);
txtName.setClickable(false);
txtName.setTextSize(5);
txtName.setMaxLines(1);
txtName.setMaxHeight(40);
txtName.setMinHeight(0);
txtName.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
txtName.setText(tagsList.get(i));
Run Code Online (Sandbox Code Playgroud)
出于某种原因,代码不能完成我想要它做的事情.请参阅我的另一个问题:其他问题
不过我现在的问题是,我可以从上面的按钮中获取该布局代码,然后使用它来制作重复按钮,就像使用列表适配器一样吗?
换句话说,我想要一个xml描述我的按钮布局,我想让它用于同一页面上的许多按钮?
您正在寻找的是膨胀.
目前,您的方法几乎没有使用XML.您正在使用代码中的某些属性创建一个实际的新按钮,而不是使用XML布局.那也没关系,顺便说一句.
无论如何,如果你想使用你的XML布局/按钮,你想使用Android的充气机:http: //developer.android.com/reference/android/view/LayoutInflater.html
那看起来有点像这样;
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
Button mButton = (Button) inflater.inflate(R.layout.button, null);
Run Code Online (Sandbox Code Playgroud)
现在你的代码中有一个按钮,从你的按钮布局中膨胀了.如果要将此多次添加到某个视图,您可能需要为每个按钮手动设置不同的标记或ID,以便以后识别它们.
归档时间: |
|
查看次数: |
2253 次 |
最近记录: |