2011-07-22 54 views
0

我很感谢以下任何帮助。如何访问自定义按钮中的xml布局

我已经创建了一个自定义组件 - 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>  

+0

从布局文件 – FoamyGuy

+0

发布XML你看着这个教程? http://blog.pocketjourney.com/2008/05/02/android-tutorial-42-passing-custom-variables-via-xml-resource-files/ – Idistic

+0

嗨,是的,我有,但我觉得有点混乱。我试图按照他们的例子操作我的代码,但它没有奏效。 – idig

回答

0

我觉得在XML,您可以指定

<packagename.MyButton 

代替

<Button 

,你将能够指定属性,就好像它是一个正常的按钮。这就是我在我的应用程序中所做的。

+0

嗨,谢谢。现在尝试过,但仍然没有运气。 – idig

+0

尝试过pocketJourney解决方案。我可以单独获取属性(在typedArray中),但将它们作为集合分配给新按钮(MyButton),它们需要位于AttributeSet中(按照构造函数)。是否有可能从TypedArray转换为AttributeSet?还是我必须在我的课堂上单独分配每个属性? – idig

0
XmlPullParser parser = resources.getXml(myResouce); 
AttributeSet attributes = Xml.asAttributeSet(parser); 

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

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

+0

嗨,谢谢。把代码放在第二个构造函数中,但出错: – idig

+0

No no。调用第二个构造函数,比如'new MyButton(getApplicationContext(),attributes);' –

+0

感谢您的帮助,但我有点白痴,如果您在回复中不能如此神秘,我会很感激。我在这个android的东西新,并试图学习,因为我去。再次感谢。 – idig