【问题标题】:How to access xml layout in custom button如何在自定义按钮中访问 xml 布局
【发布时间】:2011-10-11 08:50:13
【问题描述】:

如果有任何帮助,我将不胜感激。

我创建了一个自定义组件 - MyButton 类,它扩展了 Button。我可以在构造函数中设置属性,但我不想这样做。我想在 xml 布局文件中设置属性。如何将属性放入构造函数中,以便在活动中创建新按钮时,使用 xml 布局文件创建新按钮?

我尝试过使用充气机,但它在类扩展按钮中不起作用。还有另一种方法吗? - 我花了几个小时在网上搜索,但没有任何令人满意的结果。

提前致谢

克莱夫

这是代码

public class CustomViewModify2Activity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyButton myb = (MyButton)findViewById(R.id.mybutton1);
    myb.setText("hello");
}

}

班级:

public class MyButton extends Button {

public MyButton(Context context) {
    super(context);
    this.setBackgroundColor(getResources().getColor(R.color.Red));
}

public MyButton(Context context, AttributeSet attrs) {
    super(context, attrs);      
    this.setBackgroundColor(getResources().getColor(R.color.Yellow));
}

}

main.xml`

    <idig.za.net.MyButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/mybutton1"
    />  

`

button_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/my_button_layout">
<Button android:text="Button" android:id="@+id/button1"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:background="@color/Yellow" android:gravity="center"
    android:width="100dp" android:textStyle="bold" android:textSize="24sp"
    android:textColorLink="@color/Red"></Button>    

【问题讨论】:

  • 发布布局文件中的 xml
  • 你看过这个教程吗? blog.pocketjourney.com/2008/05/02/…
  • 嗨,是的,我有,但我觉得有点混乱。我尝试按照他们的示例操作我的代码,但没有成功。

标签: android xml layout button


【解决方案1】:
 XmlPullParser parser = resources.getXml(myResouce);
 AttributeSet attributes = Xml.asAttributeSet(parser);

然后调用第二个构造函数。

http://developer.android.com/reference/android/util/AttributeSet.html

【讨论】:

  • 没有没有。调用第二个构造函数,如new MyButton(getApplicationContext(), attributes);
  • 感谢您的帮助,但我有点白痴,如果您的回复不能如此神秘,我们将不胜感激。我是这个 android 的新手,我正在努力学习。再次感谢。
  • 这是我添加到第二个构造函数但没有运气:XmlPullParser parser = resources.getXml(myResouce); AttributeSet 属性 = Xml.asAttributeSet(parser); new MyButton(getApplicationContext(), attributes);
  • 哦,对不起,我总是假设有人有一些程序员知识,不管它是否适用于 android。 :) 很高兴帮助你。 :)
【解决方案2】:

我认为你可以在xml中指定

<packagename.MyButton 

而不是

<Button

您将能够像普通按钮一样指定属性。这就是我在我的应用程序中所做的。

【讨论】:

  • 尝试了上面提到的 pocketJourney 解决方案。我可以单独获取属性(在 typedArray 中),但要将它们作为集合分配给新按钮(MyButton),它们需要在 AttributeSet 中(根据构造函数)。是否可以从 TypedArray 转换为 AttributeSet?还是我必须在我的班级中单独分配每个属性?
猜你喜欢
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多