【问题标题】:onclick not working for inflated layoutonclick 不适用于膨胀的布局
【发布时间】:2013-06-11 06:27:52
【问题描述】:

我有一个从相对布局扩展而来的自定义类。在我的 xml 中有线性布局和里面的按钮。当我膨胀它并尝试与 onclick 一起使用时,它不起作用。但是,如果我不使用按钮,单击即可。这是代码:

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/inflated_layout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center"
          android:orientation="vertical">
        <LinearLayout
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:background="@drawable/en_ad_purplebutton">
             <Button
                    android:id="@+id/general_button"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/en_button_positive"
                    android:textColor="@color/en_white"
                    android:textSize="20sp"
                    android:clickable="true"/>
        </LinearLayout> 

自定义类:

@Override
public void onFinishInflate() {
    init();
}

private void init(){
    inf.inflate(R.layout.uc_button_positive, this);
    b = (Button)findViewById(R.id.general_button);        
}

这是我使用这个自定义类的代码

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:custom="http://schemas.android.com/apk/res/finansbank.enpara"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical" >


     <mypakage.customClass
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/view"
        android:text="deneme"
        android:onClick="go"
        android:clickable="true"
        android:layout_gravity="center"/>
 </LinearLayout>

【问题讨论】:

    标签: android layout-inflater


    【解决方案1】:

    我也试过了,发现不行, 并且发现需要做这样一个事件:

    layout = (LinearLayout) inflater.inflate(R.layout.your layout,
                container, false);
    
    
    Button b=(Button)layout .findViewById(R.id.view);
        v.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
    
            }
        });
    

    效果很好!!

    【讨论】:

    • 但我希望这个自定义类像自定义按钮一样工作,可以动态处理在 xml 的 onclick 属性中提交的任何方法。
    • 所以在自定义按钮类中添加setOnClick监听器
    • 奇怪的是当我删除线性布局内的按钮时。它有效..
    • 如果我将 setOnClickListener 添加到我的自定义类中。我需要设置一个工作,说当我点击这个任务时将被处理。但是我想在不同的活动中使用这个类有不同的方法。我想在属于活动的xml中设置onclick方法或通过活动类中的代码设置。我无法设置默认功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多