zjg_0101 2013-11-05 16:35 采纳率: 0%
浏览 835

android问题求解答??

怎么在继承View的类中怎么添加一个其他控件,例如button;或者是当继承View的类作为Activity的自定义控件时候,Activity怎么给View类传值???

  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-03-19 18:42
    关注

    该回答引用ChatGPT

    要在继承自View的类中添加其他控件,例如Button,可以通过在构造函数中创建一个新的Button对象,并将其添加到View的布局中,例如:

    public class CustomView extends View {
        private Button mButton;
    
        public CustomView(Context context) {
            super(context);
            mButton = new Button(context);
            mButton.setText("Click me");
            // 设置Button的布局参数
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mButton.setLayoutParams(layoutParams);
            // 将Button添加到View中
            addView(mButton);
        }
    }
    

    要在自定义View中接收来自Activity的值,可以使用自定义属性和XML布局文件。首先,在res/values/attrs.xml文件中定义自定义属性:

    <resources>
        <declare-styleable name="CustomView">
            <attr name="customValue" format="integer" />
        </declare-styleable>
    </resources>
    

    接下来,在CustomView的构造函数中获取自定义属性的值:

    public class CustomView extends View {
        private int mCustomValue;
    
        public CustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
            mCustomValue = a.getInteger(R.styleable.CustomView_customValue, 0);
            a.recycle();
        }
    }
    

    最后,在XML布局文件中使用自定义View时,可以设置自定义属性的值:

    <com.example.CustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:customValue="123" />
    

    在Activity中使用自定义View时,可以像使用其他控件一样访问它,并设置自定义属性的值:

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            CustomView customView = findViewById(R.id.customView);
            customView.setCustomValue(456);
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog