onClick内部实现View.OnclickListener的类永远不会被调用

时间:2017-05-18 03:50:12

标签: android

我已阅读与此类似的答案。但那并没有解决问题。这是问题情景。 MainActivity包含此片段

public class HomeFragment extends Fragment implements View.OnClickListener{  

  @Override  
  public void onClick(View view){
      Log.v("TAG",""+view.getId());  //No log message shown
      switch(view.getId()){ 
         .....   
      }  
   }   
}

片段XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/coordinatorLayout"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <RelativeLayout
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:background="@drawable/app_background">
             <ImageView
                   android:id="@+id/imageview"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:src="@drawable/ic_man" />
            <TextView
                   android:id="@+id/textview"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:layout_marginLeft="5.0dip"
                   android:layout_toRightOf="@id/imageview"
                   android:text="@string/personname"
                   android:textColor="@color/textcolor"
                   android:textSize="25.0sp" />
    </RelativeLayout>
</LinearLayout>

根据我对Onclicklistener实现的理解,任何点击视图中的任何地方都应该记录消息(这里)。没有使用滚动视图的嵌套视图。

2 个答案:

答案 0 :(得分:2)

我认为您必须忘记使用:myButton.setOnClickListener(this);

public class fragmentOne extends Fragment implements OnClickListener {
    Button myButton;

    @Override
    public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
        View myView = inflater.inflate(R.layout.fragment_home, container, false);
        myButton = (Button) myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View v) {
        // implements your things
    }
}

该按钮位于此布局fragment_home.xml中。

<Button
      android:id="@+id/myButton"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      />

答案 1 :(得分:1)

onCreateView()

中添加以下行
YourButtonName = (Button) myView.findViewById(R.id.YourButtonName);
YourButtonName.setOnClickListener(this);

和您的 onClick()就是这样。

    @Override  
      public void onClick(View view){
          Log.v("TAG",""+view.getId());  //No log message shown
          switch(view.getId()){ 
// Add your View ID here.
            case R.id.textview:
    Toast.makeText(this, "TextView Clicked", Toast.LENGTH_SHORT).show();
    break;   
          }  
       }

希望这会对你有所帮助.. :)