2011-07-22 7 views
0

私は以下のお手伝いをお願いします。カスタムボタンでxmlレイアウトにアクセスするには

Buttonを拡張するMyButtonクラスを作成しました。私はコンストラクタで属性を設定することができますが、私はこれをしたくありません。私は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" 
    /> 

`

<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
+0

からXMLを投稿を参照してください? http://blog.pocketjourney.com/2008/05/02/android-tutorial-42-passing-custom-variables-via-xml-resource-files/ – Idistic

+0

こんにちは、はい私は持っているが、私はそれが少し混乱していることがわかります。私は彼らの例に従って私のコードを操作しようとしましたが、うまくいきませんでした。 – idig

答えて

0

が、私はXMLで考えるbutton_layout.xmlは、次のように指定することができます

<packagename.MyButton 

代わりの

<Button 

、あなたはそれが通常のボタンであるかのように属性を指定することができるようになります。それが私のアプリでやったことだ。

+0

こんにちは、ありがとう。今でも試しましたが、まだ運がありません。 – idig

+0

は上記のポケット旅の解決策を試しました。私は属性を個別に(typedArray内で)得ることができますが、新しいボタン(MyButton)をコレクションとして割り当てるためには、コンストラクタごとにAttributeSet内にある必要があります。 TypedArrayからAttributeSetに変換できますか?私のクラスでは個々の属性を個別に割り当てる必要がありますか? – idig

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

次に、2番目のコンストラクタを呼び出します。

このチュートリアルを見てきました

+0

こんにちは、ありがとう。 2番目のコンストラクタにコードを挿入しますが、エラーが発生しました: – idig

+0

いいえいいえ。'new MyButton(getApplicationContext()、attributes);のような2番目のコンストラクタを呼び出す; –

+0

あなたの助けてくれてありがとうが、私はちょっとしたばかだし、あなたの返事にあまり秘密にすることができなければそれを感謝するだろう。私はこのアンドロイドのもので新しく、私が行くように勉強しようとしています。再度、感謝します。 – idig

関連する問題