setOnClickListener未在片段中调用

时间:2014-01-02 14:52:48

标签: android android-fragments

大家好我的程序中有一个问题就是没有在片段中调用setOnClickListener 在我的程序中我有三个片段,直到现在我在第一个片段代码我需要在这个片段中处理数据库,但直到现在我遇到这个问题,setOnClickListener没有调用

public class PhoneActivity extends Fragment implements View.OnClickListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {    

     super.onCreateView(inflater, container, savedInstanceState);

     View rootView = inflater.inflate(R.layout.activity_phone, container, false);

     LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.activity_phone,
             container, false);

     Button PhListBtn =(Button)mLinearLayout.findViewById(R.id.phListBtn);
     Button AddBtn =(Button)mLinearLayout.findViewById(R.id.AddBtn);

     final MySqlHelp db = new MySqlHelp(this.getActivity());



    AddBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "hi", Toast.LENGTH_LONG).show();
        }
    });
    return rootView; 



}

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
//  getMenuInflater().inflate(R.menu.phone, menu);
    return true;
}

这是xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".PhoneActivity" >

<Button
    android:id="@+id/phListBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/phoneList" 
    android:clickable="True"/>

<Button
    android:id="@+id/AddBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/AddPhone" 
     android:clickable="True"/>

1 个答案:

答案 0 :(得分:3)

删除此

 LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.activity_phone,
         container, false);

更改为

 Button PhListBtn =(Button)rootView.findViewById(R.id.phListBtn);
 Button AddBtn =(Button)rootView.findViewById(R.id.AddBtn);

此外,您不需要实施OnClickListener因为您有匿名内部类