我已经定义了一个自定义小部件(MyWidget)
RES /布局/ mywidget.xml
RES /值/ attrs.xml
码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="my_widget">
<attr name="maxValueFromTextId" format="reference"/>
</declare-styleable>
</resources>
进入我想要检索由maxValueFromTextId描述的引用对象。我的这个对象是一个TextView,它不在这个小部件中
<RelativeLayout
<TextView
android:id="@+id/text1"
/>
<Mywidget
maxValueFromTextId="@id/text1"
/>
/>
那么在MyWidget.java中做什么来获取TextView引用对象?
我读了这篇有用的文章: Defining custom attrs
由于
答案 0 :(得分:1)
为自定义视图定义其他属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ColorOptionsView">
<attr name="titleText" format="string" localization="suggested" />
<attr name="valueColor" format="color" />
</declare-styleable>
</resources>
要在布局文件中使用这些属性,必须在XML标头中声明它们。在下面的清单中,这是通过代码的xmlns:custom部分完成的。这些属性也分配给视图。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
<!-- define new name space for your attributes -->
xmlns:custom="http://schemas.android.com/apk/res/com.vogella.android.view.compoundview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- Assume that this is your new component. It uses your new attributes -->
<com.vogella.android.view.compoundview.ColorOptionsView
android:id="@+id/main_color_options"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
custom:titleText="Background color"
custom:valueColor="@android:color/holo_green_light"
/>
</LinearLayout>
在您的活动中
public class MainActivity extends Activity {
@Override
protected void onCreate( final Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
this.setContentView( R.layout.activity_main );
final ColorOptionsView colorOptionsView = ( ColorOptionsView ) this.findViewById( R.id.main_color_options);
}
}